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 9 years ago.
I'm currently working on a little form that allows people to book a stay at a hostel. Basicly, I get them to pick two dates. (Day of arrival & day of departure) Then I want to calculate the difference between those dates in days, and finally I want to multiply the number of days with the price per day.
I can't seem to figure out how to calculate the days * price per day and pass that string on to the "amount value" in my form.
This is what I got so far:
<input type="text" id="datepicker" value="arrival (day-month-year)" />
<input type="text" id="datepicker2" value="departure (day-month-year)" />
<form action="checkout.php" method="post">
<input name="amount" type="hidden" value="$dateDiff * price per day = value">
<input type="submit" value="Check out" id="checkout">
</form>
And my PHP
<?php
$date1 = ("#datepicker");
$date2 = ("#datepicker2");
$dateDiff = $date1 - $date2;
$fullDays = floor($dateDiff/(60*60*24));
echo "Difference is $fullDays days";
?>
Edit: After the first two comments, let me explain that I'm fairly new to PHP. Thanks.
You have to put the input fields in your form and give it a name likes this:
<form action="checkout.php" method="post">
<input type="text" id="datepicker" name="datepicker" value="arrival (day-month-year)" />
<input type="text" id="datepicker2" name="datepicker2" value="departure (day-month-year)" />
<input name="amount" type="hidden" value="$dateDiff * price per day = value">
<input type="submit" value="Check out" id="checkout">
</form>
Now in your PHP file:
<?php
if(isset($_POST["datepicker"], $_POST["datepicker2"])){
$date1 = new DateTime($_POST["datepicker"]);
$date2 = new DateTime($_POST["datepicker2"]);
$diff = $date1->diff($date2);
$amount_per_day = 10; // for example 10 dollars
$total = floor($diff["days"]) * $amount_per_day; // total
}
?>
The datetime object offers a diff function:
http://php.net/manual/en/datetime.diff.php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
print_r($interval);
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 2
[h] => 0
[i] => 0
[s] => 0
[invert] => 0
[days] => 2
)
So you could calculate your price with
$price = $pricePerDay * $interval->days;
Try this:
function dateDiff($start, $end)
{
$start_ts = strtotime($start);
$end_ts = strtotime($end);
$diff = $end_ts - $start_ts;
return round($diff / 86400);
}
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
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 9 years ago.
$start_date = "2012-01-05";
$end_date = "2012-02-10";
How to get month and after getting month date should like in above example
$end_date should "2012-02-05"; leave above 5 days. don't count a above day.
How can i do this in php?
I wan't to like
$month = 1;
$end_date = "2012-02-05";
Second Example
$start_date = "2012-06-19";
$end_date = "2012-09-25";
then should
$month = 3;
$end_date = "2012-09-19";
Leave days between "2012-09-19" to "2012-09-25".
Thanks
$start = '2012-01-23';
$months = 12;
$date=new DateTime($start);
$date->modify('+'.$months.' month');
echo $date->format('Y-m-d');
You can use strtotime() to just add a number of months to your original date...
$start = '2012-01-23';
$months = 3;
$timeExpr = sprintf('+%d months', $months);
$end = date($start, strtotime($timeExpr));
echo $end; //will output '2012-04-23'
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 want to compute the next Xth day in the calendar.
For example today is 2012-10-08. if X=25 i want it to return 2012-10-25 but if X=06 i want 2012-11-06. If the month doesn't have the required X days, it must return the last day of the month (if i'm looking for the 30th of february for example, it must return 28 or 29 if leap year)
It seems simple enough but I get caught by all the special cases (last month of the year, 28-31 day months, etc).
You can use strtotime() and t:
$x = 5; // given day
if(date('t') < $x){ // check if last day of the month is lower then given day
$x = date('t'); // if yes, modify $x to last day of the month
}
$month = date('m'); // current month
if(date('d') >= $x){ // if $x day is now or has passed
$month = $month+1; // increase month by 1
}
$year = date('Y'); // current year
if($month > 12){ // if $month is greater than 12 as a result from previous if
$year = date('Y')+1; // increase year
$month = 1; // set month to January
}
if(date('t', strtotime($year.'-'.$month.'-01')) < $x){ // check if last day of the new month is lower then given day
$x = date('t', strtotime($year.'-'.$month.'-01')); // if yes, modify $x to last day of the new month
}
$date = date('d F Y', strtotime($year.'-'.$month.'-'.$x));
// 05 November 2012
HERE is a nice tutorial.
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
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.