This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Php.Advance weekly calendar one week
I have written a script that displays a calendar week by week that the user can chose to go back or forward a week at a time. Everything works great except the first week of every year still displays the wrong year and the 31st December shows as 02/01. It seems that only week 1 is affected, the days are correct again in week and onwards
<?
if(isset($_POST['add_week'])){
$last_week_ts = strtotime($_POST['last_week']);
$display_week_ts = $last_week_ts + (3600 * 24 * 7);
} else if (isset($_POST['back_week'])) {
$last_week_ts = strtotime($_POST['last_week']);
$display_week_ts = $last_week_ts - (3600 * 24 * 7);
} else {
$display_week_ts = floor(time() / (3600 * 24)) * 3600 * 24;
}
$week_start = date('d-m-Y', $display_week_ts);
$week_number = date("W", $display_week_ts);
$year = date("Y", $display_week_ts);
echo $week_start.' '.$week_number.' '.$year;
?>
<table name="week">
<tr>
<?
for($day=1; $day<=7; $day++)
{
echo '<td>';
echo date('d-m-Y', strtotime($year."W".$week_number.$day))." | \n";
echo '</td>';
}
?>
</tr>
<tr>
<form name="move_weeks" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="last_week" value="<? echo $week_start; ?>" />
<td colspan="7"><input type="submit" name="back_week" value="back_week" /><input type="submit" name="add_week" value="add_week" />
</td>
</form>
</tr>
</table>
Any help will be appreciated
As suggested in the answer to the original question, you need to not use the week number and year number stuff.
If at the end of the day, you want to be able to list seven days for the week, just do not use this section of code at all:
$week_number = date("W", $display_week_ts);
$year = date("Y", $display_week_ts);
echo $week_start.' '.$week_number.' '.$year;
And replace the loop that echos out with the loop suggested in the original question.
This has to do with the format you are providing date(). Specifically W.
From the PHP Docs:
ISO-8601 week number of year, weeks starting on Monday
It is coincidence this is appearing because December 31, 2012 is a Monday.
You should rewrite your code to use other ways to calculate dates. I'd recommend against trusting form data.
Related
I have been given an assignment to build a point of sale system. The customer will be charged based on their age.If the user is older that 15.5 years they will be charge $50 for a product. If the user is younger that 15.5 years they will be charged $25.
This is the code that I have so far:
<html>
<head>
<title>Age Test</title>
</head>
<body>
<form action="age_test.php" method="post">
<input type="text" name="first" placeholder="Enter first name">
<br>
<input type="text" name="last" placeholder="Enter last name">
<br>
<input type="date" name="date">
<br>
<label for="rush"> Check for a rush order(A $200 fee will apply.)</label>
<input type="checkbox" name="rush">
<br>
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
// echo "submit is set";
$date = $_POST['date'];
$age = date("Y/m/d") - $date;
echo $age;
//Users age will determine the price.
if($age >= 15.5){
echo "<br>Your price is $50";
}elseif ($age < 15.5) {
echo "<br>Your price is $25";
}
if(isset($_POST['rush'])){
// echo "<br>$200 is applied to payment";
}
}
?>
</body>
</html>
The solution that I have does not give me a decimal as a result. I would like some help on how to produce a decimal as a result. Any help will be greatly appreciated.
I think you're looking for the number_format function in this case.
string number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )
Here's an example relevant to your assignment:
number_format((float)$age, 2, '.', '');
Check out the documentation for it.
Try simple way :)
<?php
$input = '1970/01/01'; // $_POST['date']
$now = new \DateTime();
$diff = $now->diff(new \DateTime($input));
$price = ($diff->y > 15 && $diff->m > 6) ?50 : 25;
echo $price;
Here's a way to calculate it, also considering the timezone.
I've updated the answer to calculate with months instead.
$dateInput = $_POST['date'];
$timeZone = new DateTimeZone('America/New_York');
$bday = DateTime::createFromFormat('Y/m/d', $dateInput , $timeZone);
$diff = $bday->diff(new DateTime());
$months = $diff->format('%m') + 12 * $diff->format('%y');
//returned number of months and divide by 12.
//12 months make a year.
$age = $months/ 12;
echo $age;
This will return a float by default.
//And you can always round to 2 decimal places
echo number_format((float)$age, 2, '.', '');
Hope this helps
<?php
// your date you will display from database
$date = "2012-05-06";
$date = new DateTime($date);
/*
* for the current year,month and day you will
* date('y') --> to print current day
* date('m') --> to print the current month
* date('y') --> to print the current day
*/
$y = date('Y');
$m = date('m');
$d = date('d');
$full_date ='P'.$y.'Y'.$m.'M'.$d.'D';
/*
for example
* we will subtract (2012-05-06) - (2017-07-26)
*
* -0006 for year and 02 month and 20 day
*
*/
$date ->sub(new DateInterval(".$full_date."));
/*
* you should ltrim (-) from years
*/
$str = ltrim($date ->format('y'),'-');
/*
* you should ltrim (0) from month
*/
$str2 = ltrim($date ->format('m'),'0');
//output 1
echo $str.' years and '.$str2 .' months';
// output 2
echo $str.'.'.$str2;
?>
The output will be
6 years and 9 months
6.9
For more information about subtract date and time check this link subtract date and time
The problem with your calculation
$age = date("Y/m/d") - $_POST['date'];
is that - regardless of the date format used on the client side - you are effectively trying to subtract two string values from each other, resulting in them implicitly being casted to ints.
That is, as long as both strings start with the year, the calculation appears to work; except that it never contains the fraction you are looking for.
See https://3v4l.org/qskMD for an example.
As a solution to your problem, try calculating the difference in years first, then find the remaining days, and divide by the number of days in a year:
// create a `DateTimeImmutable` object from the date provided (adjust format as needed)
$birthday = \DateTimeImmutable::createFromFormat(
'Y-m-d',
$_POST['date']
);
// current date and time
$now = new \DateTimeImmutable();
// find the total difference
$totalDifference = $now->diff($date);
// get difference in total years only
$years = (int) $difference->format('y');
// create a `DateTimeImmutable` object, going back full years from now only
$yearsAgo = $now->diff(new \DateInterval(sprintf(
'P%sY',
$years
));
// get difference between birthday and going back full years
$remainingDifference = $yearsAgo->diff($birthday);
// get difference in months
$months = $remainingDifference->format('m');
$age = $years + $months / 12;
For reference, see:
http://php.net/manual/en/class.datetimeimmutable.php
http://php.net/manual/en/class.dateinterval.php
Hi I am new to javascript and php. I have a form that has three text boxes, starttime, endtime and results. I am trying to take the starttime and endtime and find how much time has passed and display this in the results. How can I go about this?
here is my html:
<form action="JobChangeTimeSheet.php" method="GET">
Machine Stopped at:
<input type="time" name="start_date"/>
End of TO:
<input type="time" name="since_start"/>
<input type="submit">
Total time
<?PHP
if (! empty($_GET['start_date'])){
$start_date = new DateTime($_GET['start_date']);
$since_start = $start_date->diff(new DateTime($_GET['since_start']));
echo $since_start->days.' days ';
echo $since_start->h.' hours';
echo $since_start->i.' minutes';
}
?>
</form>
You can see there are 2 text boxes, a button, and a third disabled text box. I am trying to view the difference in minutes between the two text boxes in the third text box
Since you do not have a code I can work on, I will guide you exactly through the steps on how to do this.
Load your HTML input in PHP vars named $start_date and $end_date. Use these lines:
$start_date = new date("Y-m-d H:i:s",strtotime($start_date));
$end_date = new date("Y-m-d H:i:s",strtotime($end_date));
$interval = $start_date->diff($end_date);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Difference in minutes is: '.($hours * 60 + $minutes);
PS: You are talking about Javascript in your question but no Javascript code has been presented in your code. Are you using some sort of DateTimePicker?
I have a script that counts how many days have past since the start date stored in my database.
The theory is, a user signs up and has 7 days to complete registration, from the admin side of things, this script is used to monitor where a user is upto and how many days have past since they registered.
So in this example we give the user 7 days grace in which to complete. This echos out like '(number of days out of 7 have past'
Then after 7 days this should change to give the number of days overdue. so if a user has 7 days to complete and they take 8 days then this will take into account the first 7 days grace and then have an overdue date of 1 day.
so for instance it should echo out '1 day overdue', rather than what it is currently doing and saying 8 days overdue, i am trying to do this by minusing the first 7 days.
i have been told this will help however i am having trouble getting it to work with my date variable
$pre_date=date('Y-m-d', strtotime('-7 days'));
heres my compelte code, please can someone show me where i am going wrong
<?php include 'config.php';
$data = mysql_query("SELECT *,
TIMESTAMPDIFF(DAY, date, CURDATE()) AS expire_date
FROM supplier_session
ORDER BY expire_date ASC")
or die(mysql_error());
echo "<table class=\"table\" style=\"width:995px; font-family: 'Lucida Grande', Tahoma, Verdana, Arial, sans-serif;
font-size:11px;\" >
<tr>
<td style=\"width:100px;\">ID:</td><td>Company Name:</td><td>Company Reg No:</td><td>Application Started:</td><td style=\"width:200px;\">Application Duration:</td><td style=\"width:100px;\">Date:</td><td>Status:</td></tr>";
while($row = mysql_fetch_array( $data )) {
$days = $row['expire_date'];
$when = $days*0;
$str = $row['expire_date'];
$str2 = substr($str, 0); // "quick brown fox jumps over the lazy dog."
$pre_date=date('Y-m-d', strtotime('-7 days'));
if ($when <= 31){
echo "<tr><td style=\"width:100px;\"><p>".$row['id'] . "</p></td>";
echo "<td style=\"width:150px;\"><p>".$row['company_name'] . "</p></td>";
echo "<td style=\"width:150px;\"><p>".$row['company_reg_number'] . "</p></td>";
echo "<td>"; echo date('d/m/Y',strtotime($row['date'])); echo "</td>";
if ($days >= 8) {
echo "<td style=\"width:200px;\"><p>{$pre_date} days overdue</td>";
}
elseif ($when <= 7){
echo "<td style=\"width:200px;\"><p>{$str2} of 7 days past</td>";
}
}
echo "<tr>";
}
echo "</table>"; //Close the table in HTML
?>
You've forgotten to pass the date variable to strtotime, so you are always substracting 7 days to the actual date and getting 8 as a result.
Try with a subraction of the actual date minus the expire date in order to get the number of days that have past.
I think u have some mistake in ur function
$pre_date=date('Y-m-d', strtotime('-7 days'));
For example u can try to use somth like that
$datetime = date("Y-m-d", strtotime( date( 'Y-m-d' )." +2 days"));
Result of function looks like:
2014-05-08
Also there more information what u need:
Click.
With unixtime looks like that. We take difference between 2 dates in second and divide it on number of seconds in day
<?php
date_default_timezone_set('UTC');
$now_time = time();
$date_before = time()-(7*24*60*60);// 7 days; 24 hours; 60 mins; 60secs
echo($now_time);
echo('<br>');
echo($date_before);
echo('<br>');
$difference = $now_time - $date_before;
$result = intval($difference/(24*60*60)); //seconds in day
echo($difference);
echo('<br>');
echo($result);
also u can get time from date with:
$unixtime = strtotime('22-09-2008');
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to create a weekly calendar that allows the user to advance or go back a week. So far I have this...
<?
if(isset($_POST['add_week'])){
$last_week_ts = strtotime($_POST['last_week']);
$display_week_ts = $last_week_ts + (3600 * 24 * 7);
} else if (isset($_POST['back_week'])) {
$last_week_ts = strtotime($_POST['last_week']);
$display_week_ts = $last_week_ts - (3600 * 24 * 7);
} else {
$display_week_ts = floor(time() / (3600 * 24)) * 3600 * 24;
}
$week_start = date('d-m-Y', $display_week_ts);
$week_number = date("W", strtotime( $display_week_ts));
$year = date("Y", strtotime( $display_week_ts));
echo $week_start.' '.$week_number.' '.$year;
?>
<table name="week">
<tr>
<?
for($day=1; $day<=7; $day++)
{
echo '<td>';
echo date('d-m-Y', strtotime($year."W".$week_number.$day))." | \n";
echo '</td>';
}
?>
</tr>
<tr>
<form name="move_weeks" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="last_week" value="<? echo $week_start; ?>" />
<td colspan="7"><input type="submit" name="back_week" value="back_week" /><input type="submit" name="add_week" value="add_week" />
</td>
</form>
</tr>
</table>
The the back and forward buttons work just fine and the $week_start variable which represents the first date of the week advances and goes back as it should but regardless of the date shown the $week_number and $year show as 01 and 1970 or 36 and 1600.
I know it must be something to do with the way I have tried to extract them from $display_week_ts but I don't know what
The following looks out of place:
$week_start = date('d-m-Y', $display_week_ts);
$week_number = date("W", strtotime( $display_week_ts));
$year = date("Y", strtotime( $display_week_ts));
See how you're using $display_week_ts in the first statement, but for the other (and similar) statements, you wrap that timestamp inside a call tostrtotime() which returns false.
It's best to just drop the strtotime() and use the variable as is:
$week_number = date("W", $display_week_ts);
$year = date("Y", $display_week_ts);
Ok, fixed it, I needed to get the week number and year from $week_start instead
How do you create a select with the option of 2 days ahead from today picked as the default option (i.e. a 48 hour window) in PHP? This is the code I'm using so far but it doesn't work unfortunately!
<?php
$weekday = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
$days = range (1, 31);
$currentDay = date('F');
echo "<select name='weekday'>";
foreach ($days as $value) {
$default = ($value == $currentDay)?'selected="selected"':'';
echo '<option '.$default.' value="'.$value.'">'.$value."</option>\n";
}
echo '</select> ';
?>
I'm confused as to what your code does.
As far as I can tell $weekday is not used after being instantiated, and you are setting $currentDay to the text representation of the current month (e.g. September).
But if you want to get the day of month of the day 48 hours from now:
$two_days_ahead = date('j', strtotime('+ 48 hours'));