I Have a php script
if (isset($_POST['getdays'])) {
$birthday = $_POST['daysalive'];
$now = date("Y-m-d");
$days_alive = date_diff(date_create($birthday), date_create($now));
}
Which returns me the amount of days a user lives by echoing:
$days_alive->format('%a days old');
<input name="daysalive" type="text" class="mt-3" placeholder="12-12-2018">
<button name="getdays" class="btn btn-primary mt-3" type="submit">Check in what year you will be 20000 days old</button>
What I would like to do is take this input and determine in what year the user would be 20000 days old. I was thinking of looping through $days_alive using a for() loop with an if statement like so:
if($days_alive + 365 >= 20000) {
echo(date('Y');
}
any thoughts?
PHP has a date_add function which allows you to add a DateInterval to a DateTime object. So you just need to add a DateInterval of 20000 days like so:
date_add(date_create($birthday), new DateInterval('P20000D'));
There is no need for loops. You can use strtotime or DateTime to calculate it.
$birthday = "1975-01-01";
$res = strtotime($birthday . " + 20000 days");
echo date("Y-m-d", $res); //2029-10-04
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
I have a number 144 i want to convert to months and days, i.e. I want to display 3 months 24 days.
What is the formula to do it? I have tried many methods but no use.
$sub_struct_month = ($result[0] / 30) ;
$sub_struct_month = floor($sub_struct_month);
$sub_struct_days = ($result[0] / 30); // the rest of days
$sub_struct = $sub_struct_month."m ".$sub_struct_days."d";
Use the Modulus operator to get the proper number of days:
<?php
$result = array(144);
$sub_struct_month = ($result[0] / 30) ;
$sub_struct_month = floor($sub_struct_month);
$sub_struct_days = ($result[0] % 30); // the rest of days
$sub_struct = $sub_struct_month."m ".$sub_struct_days."d";
echo $sub_struct;
?>
Results in 4m 24d.
More details: http://php.net/manual/en/language.operators.arithmetic.php
You know that there are leapyears (February has 29 days sometimes)? And for example July and August have 31 days. You can't say generally "convert 144 days to months" because it's different for every month.
<?php
$start_date = new DateTime(date("Y/m/d"));
$end_date = new DateTime(date("Y/m/d",strtotime("+144 days")));
$dd = date_diff($start_date,$end_date);
echo "$dd->m months $dd->d days";
?>
for start_date you can use a specific date! also for end_date
this is the correct way, so every leapyear and everything is observed!
PHP has perfect class to work with dates: DateTime
This class allow you get difference between two dates DateTime::diff and format result as you want using DateTime::format
Yes, it's not exactly what you want. But it allow you get precise value of days and months.
So, I suggest you read the docs at first. I hope you will find a way how to implement it in your case.
please try below code
$months = floor(144 / 30);
$days = 144 - ($months*30);
echo $months ."Months " . $days ."days";
My way to do it
$days = 144;
$month = $days/30;
list($month,$days) = explode(".",$month);
$days = "0.".$days;
echo $month."</br>";
echo $days*30;
Example:
$difference = strtotime($to) - strtotime($from);
$months = ($difference / 86400 / 30 );
Problem: But this way I never get exact average. Because I can’t sure for 30 days there can be 31 and 28 days months also.
Even I tried to divide by 12 month average but that also can’t work in every month selection cases
read first and
change according to ur own
You can get number of days for certain month in certain year using this function:
PHP Manual - cal_days_in_month
You can get number of days for whole year using, for example, this solution:
Finding the total number of days in year
Also, if you just want to get number of days for current month, you can use this:
date("t");
Are you after the number of months in a date range? If so, you could modify this previous answer to handle what you want:
PHP: Loop through all months in a date range?
To what I think you're after, you'd do something like this
$date_from = strtotime("2013-08-01");
$date_to = strtotime("2013-10-01");
$month_count = 0;
while ($date_from < $date_to) {
$date_from = strtotime('+1 month', $date_from);
$month_count++;
}
// month_count = number of months covered in the date range
Or, if you're just looking for the number of days in a date range, you could do something like this:
$date_from = strtotime("2013-08-01");
$date_to = strtotime("2013-08-28");
$diff = $date_to - $date_from;
$days_in_range = floor($diff / (60*60*24));
//days_in_range = 27
Not entirely sure what you're after from your question.
Good Day,
I am trying to create a recurring date system that has the following:
nth day of nth month (2nd day of every 3rd month)
$this_months_friday = strtotime('+3 days +4 months');
the output of that will always be current day + 3 days of the 4th month.
how do I get it to display the nth day of the nth month?
since i also tried
$this_months_friday = strtotime('every 3 days +4 months');
and it did not return any result. Should i stick with strtotime on this one or move to DateTime function of php. though i wont still be able to formulate the proper argument for that kind of date sequence.
Any help would be greatly appreciated.
Thank You.
Probably better off using DateTime with a couple intervals:
$d = new DateTime();
$d->add(new DateInterVal('P' . $days . 'D'))->add('new DateInterVal('P' . $months . 'M'));
not sure what youre two example intervals are wanting.
You want an internval to start in 4 months, which then repeats every 3 days?
That'd be something more like
$d = new DateTime();
$d->add(new DateInterval('P4M')); // jump ahead 4 months immediately
$day3 = new DateInterval('P3D');
for ($i = 0; $i < 100; $i++) {
$d->add($day3); // jump ahead 3 days
... do something with this new date
}
for a basic recurring event, +4 months + 3 days, you'd simply have one interval:
$interval = new DateInteval('P4M3D'); // +4 months +3 days
$date = new DateTime();
while($some_condition) {
$date->add($interval);
do_something();
}
You can do this by saving the values in variables like that :
$day=3;
$month=4;
echo date("d-m-y",strtotime('+'.$day .'days' .'+'.$month.'months'));
Explanation:
7(july)+4 months = 11 month(November)
8 july+ 3 days = 11 july
Output:
11-11-13
NOTE: just for the example I have put the values hard coded, You can make them dynamic.
This question already has answers here:
Get interval seconds between two datetime in PHP?
(8 answers)
Closed last year.
HI, i have a couple of posts in my MySql database server, one of the info content in each post is the date and time in the format datetime (Ex. 2010-11-26 21:55:09) when the post was made.
So, i want to retrive the actual date and time from the SQL server with the function NOW() and calculates how many seconds or minutes or hours or days ago was post the info.
I dont know how to create this php script but i know that for sure is allready made, so thanks for any help.
you could use the date_diff() function
http://php.net/manual/en/function.date-diff.php
Something like...
<?php
$now = time();
$then = $posttime;
$diff = date_diff($now,$then);
echo $diff->format('%R%d days'); #change format for different timescales
?>
edit --
I actually solve this issue on one of my twitter apps using this function...
function time_since ( $start )
{
$end = time();
$diff = $end - $start;
$days = floor ( $diff/86400 ); //calculate the days
$diff = $diff - ($days*86400); // subtract the days
$hours = floor ( $diff/3600 ); // calculate the hours
$diff = $diff - ($hours*3600); // subtract the hours
$mins = floor ( $diff/60 ); // calculate the minutes
$diff = $diff - ($mins*60); // subtract the mins
$secs = $diff; // what's left is the seconds;
if ($secs!=0)
{
$secs .= " seconds";
if ($secs=="1 seconds") $secs = "1 second";
}
else $secs = '';
if ($mins!=0)
{
$mins .= " mins ";
if ($mins=="1 mins ") $mins = "1 min ";
$secs = '';
}
else $mins = '';
if ($hours!=0)
{
$hours .= " hours ";
if ($hours=="1 hours ") $hours = "1 hour ";
$secs = '';
}
else $hours = '';
if ($days!=0)
{
$days .= " days ";
if ($days=="1 days ") $days = "1 day ";
$mins = '';
$secs = '';
if ($days == "-1 days ") {
$days = $hours = $mins = '';
$secs = "less than 10 seconds";
}
}
else $days = '';
return "$days $hours $mins $secs ago";
}
You pass it in a unix timestamp of the time to check (the post time) and it returns the various string.
As billythekid said, you can use the date_diff() function if you are using PHP5.3+, if you are not then there are various methods. As shown by other posters. The quickest method in MySQL if you want to know the time split in to the "hours:mins:secs" hierarchy is to use the TIMEDIFF() function.
SELECT TIMEDIFF(NOW(), '2010-11-26 12:00:00');
If you want it as seconds, use the unix timestamp features in MySQL or in PHP, you can convert MySQL dates to PHP quickly using strtotime().
Usually, you do this kind of thing in a query, but MySQL isn't very good with intervals (it would be very easy with PostgreSQL). You could convert it to unix timestamp, then it would give the number of seconds between the two dates :
SELECT UNIX_TIMESTAMP() - UNIX_TIMESTAMP(your_datetime_column);
I thought about DATEDIFF, but it only returns the number of days between the two dates.
You can do it in PHP, for instance, with DateTime class :
$date1 = new DateTime();
$date2 = new Datetime('2010-11-26 12:00:00');
var_dump($date1->diff($date2));
(There's a procedural way to do this, if you're not a fan of OOP.)
This is definitely the solution I'd use if I can't do it with the RDBMS. DateTime::diff returns a DateInterval object, which contains the number of seconds, minutes, hours, days, etc. between the two dates.
You could also do it with timestamps in PHP :
$num_sec = time() - strtotime('2010-11-26 12:00:00');
Which would return the same thing as the SQL query.
An easy solution is possible from within the SQL Query:
SELECT UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(post_date) AS seconds_ago FROM posts
Documentation here: MySQL Ref
I actually needed to do this in PHP myself and while billythekid's post was in the right direction it fell short. I've minimized the code though it should be clear that the second parameter is from a database with a DATETIME column type.
<?php
$interval = date_diff(date_create(date('Y-m-d H:i:s')), date_create($row1['date']));
echo $interval->format('%R%a days');
//Database: 2019-02-22
//PHP's date: 2018-07-07
//Result: +306 days
?>
A reminder of the obvious: you can also just use substr($interval->format('%R%a days'),1) if you need just the integer.