Today is 2014-11-16.
I got these three dates in the future but I want them to be only one date instead.
2014-12-15 21:27:12
2014-12-15 21:32:20
2014-12-16 12:22:09
I want to get the total end date from today. That would be aproximately three month into the future but how can i calculate it to be the same date each time from the three dates above?
How can this be achieved with PHP's DateTime and DateInterval classes?
This might help:
$dateTimeObject=new DateTime(date('Y-m-d h:i:s', strtotime('2014-12-16 12:22:09')));
//to get diff with now
$diff = $dateTimeObject->diff(new DateTime(date('Y-m-d h:i:s')));
Then,
//to get diff months
echo $diff->m;
//to get diff hours
echo $diff->h;
//to get diff minutes
echo $diff->i;
And so on.
It is highly recommended to take a look at the PHP's DateTime official document.
Note that, DateTime is available on PHP >=5.2.0
Related
I have a problem here I want to get the +4 week date from the current date using carbon, the +4 week plan will be dynamic depending on the input entered by the user, how do I make it, I've tried using this code but it's time to step back
$dt = Carbon::now();
dd($dt->week(4)->format('Y-m-d'));
Check Carbon docs, you may use addWeeks():
$dt = Carbon::now();
dd($dt->addWeeks(4)->format('Y-m-d'));
The week() method you've used, sets the week number using given first day of week and first day of year included in the first week.
I am not sure to understand your question, but I guess you just have to use :
$dt = Carbon::now();
$dt->addWeeks(4);
dd($dt->format('Y-m-d');
You don't need carbon for such simple tasks.
With DateTime
echo date_create('+4 weeks')->format("Y-m-d");
or with date and strtotime
echo date("Y-m-d",strtotime('+4 weeks'));
This question already has answers here:
Convert one date format into another in PHP
(17 answers)
How to calculate the difference between two dates using PHP?
(34 answers)
Timezone conversion in php
(9 answers)
Adding three months to a date in PHP
(11 answers)
Closed 4 years ago.
Everyone has to deal with date/time formatting, time zones, weird time formats, etc. at some point in programming. PHP has few ways to deal with these problems, the most notable of which is PHP's built in DateTime class. This is because the DateTime class acts as an all-in-one solution to all theses problems.
However, the DateTime class has one flaw: it can be confusing to use if you aren't already familiar with it.
This post is to help those people who have want to know more about the DateTime class and/or found themselves asking one of the following questions:
How do I convert a string to a modifiable date/time?
How do I format a date/time string?
How do I get the difference between 2 times?
How do I account for time zones?
Please Note:
This post will not be addressing the usage of date(), time(), strtotime(), or any of their related functions. This post is purely to explain the correct usage of the DateTime and its related classes in PHP. While many of these answers can also be achieved via date() and its related functions, DateTime wraps all of that functionality into a few clean classes; which can make it easier to comprehend as a whole.
Most of the below information can be gotten from various parts of PHP's documentation of the DateTime class. However, this answer is formatted in a way that should answer most people's questions regarding the DateTime class, and should apply to most of its use cases.
If you are trying to do something more advanced with Dates/Times such as creating a DateTime wrapper, using immutable DateTime instances, or something else that's specific to your applications needs I highly suggest you checkout the full Date and Time documentation.
1. How do I convert a string to a modifiable date/time?
One of the hardest things to do in programming is to try and make end-user input usable. However, when it comes to dates and times, the DateTime class makes this practically child's play.
How
DateTime's constructor uses a powerful parser that accepts most widely known formats including relative formats.
$datetime = new DateTime($datetime_string);
From there you can use any of the following methods to modify the time:
$datetime->modify() - Alters the timestamp (works great with relative formats!)
$datetime->add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
$datetime->sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
$datetime->setDate() - Sets the date
$datetime->setISODate() - Sets the ISO date
$datetime->setTime() - Sets the time
$datetime->setTimestamp() - Sets the date and time based on an Unix timestamp (great for dealing with absolute times across time zones!)
To see the full list of formats that DateTime::__construct() supports check out: Supported Date and Time Formats.
Example - Interpreting End-User Input
Lets say you have form that allows users to say what day they want to make an appointment, but this input is not a date picker with a forced format, but is instead a plain text input.
A typical end-user will put something like these in that input and a typical programmer will respond in the following ways when asked to support it:
12/31/2000 - "OK"
2000-12-31 - "Sure"
Today - "Um, I guess we could support that?"
Tomorrow - "I guess we should support that too."
wednesday next week - "No."
After a while you either force a specific format (which you should always do anyway) or weep at your poor form design. However, DateTime allows all of these as valid inputs and interprets them flawlessly.
// 2000-12-31 00:00:00.000000
new DateTime('12/31/2000');
// 2000-12-31 00:00:00.000000
new DateTime('2000-12-31');
// 2000-12-31 00:00:00.000000
new DateTime('Today');
// 2001-01-01 00:00:00.000000
new DateTime('Tomorrow');
// 2001-01-03 00:00:00.000000
new DateTime('wednesday next week');
However, like most things the DateTime class is not perfect, and doesn't support every format. Which is why you should always use try ... catch blocks with DateTime and confirm with your end-user that the date you interpreted is what the end-user desired. One great example is European date formats:
try {
new DateTime('31/12/2000');
} catch (Exception $e) {
echo $e->getMessage();
}
Output:
DateTime::__construct(): Failed to parse time string (31/12/2000) at position 0 (3): Unexpected character
Example - Modifying A Date/Time
You can adjust any date/time easily with the $datetime->modify() method:
$datetime = new DateTime('2001-01-01');
// 2001-01-04 00:00:00.000000
$datetime->modify('+3 days');
// 2001-02-04 00:00:00.000000
$datetime->modify('+1 month');
// 2001-02-03 23:59:00.000000
$datetime->modify('-60 seconds');
// 2001-02-02 00:00:00.000000
$datetime->modify('yesterday');
// 2001-02-02 18:00:00.000000
$datetime->modify('6pm');
The $datetime->modify() method is the easiest way to modify any instance of DateTime.
However, due to parsing it is somewhat inefficient. If you are modifying 1000's of dates/times and you need better performance, then use add(), sub(), setDate(), setISODate(), setTime(), and setTimestamp() instead of modify().
$datetime = new DateTime('2001-01-01');
// 2001-06-01 00:00:00.000000
$datetime->setDate(2001, 6, 1);
// 2001-06-01 06:30:00.000000
$datetime->setTime(6, 30, 0);
// No sane person should ever do the below when they could just add 10,000
// seconds, but it's a good way to test how fast your system will handle
// updating DateTime.
$timestamp = $datetime->getTimestamp();
foreach (range(1, 10000) as $i) {
$timestamp++;
$datetime->setTimestamp($timestamp);
}
// 2001-06-01 09:16:40.000000
2. How do I format a date/time string?
It's common that you need to take 1 date/time string and format it as another date/time string, or even just take and existing date/time and update it. The DateTime class makes this simple as well.
How
DateTime has the method format() which returns the date/time as a formatted string.
$datetime = new DateTime;
$format = 'Y-m-d H:i:s';
echo $datetime->format($format);
We are only going to use a small subset of the formatting options available in these examples, so I highly encourage you to checkout the documentation on formatting dates/times as well as the predefined DateTime constants.
Notice: Be aware that if you attempt to escape a character that could be PHP string escape character you may get unexpected results.
Incorrect Result
// output: Da e 2000-12-31
echo $datetime->format("\D\a\t\e\: Y-m-d").PHP_EOL;
Correct Result
// output: Date 2000-12-31
echo $datetime->format("\D\a\\t\e\: Y-m-d").PHP_EOL;
// output: Date 2000-12-31
echo $datetime->format('\D\a\t\e\: Y-m-d').PHP_EOL;
Examples
These are some common formats that you may need:
SQL Dates/Times
// output: 2000-12-31
echo $datetime->format('Y-m-d').PHP_EOL;
// output: 23:59:59
echo $datetime->format('H:i:s').PHP_EOL;
// output: 2000-12-31 23:59:59
echo $datetime->format('Y-m-d H:i:s').PHP_EOL;
End-User Readable Dates/Times
// output: 12/31/2000
echo $datetime->format('n/j/Y').PHP_EOL;
// output: 11:59pm
echo $datetime->format('g:ia').PHP_EOL;
// output: 12/31/2000 at 11:59pm
echo $datetime->format('n/j/Y \a\t g:ia').PHP_EOL;
// output: Sunday the 31st of December 2000 at 11:59:59 PM
echo $datetime->format('l \t\h\e jS \o\f F Y \a\t g:i:s A').PHP_EOL;
Dates/Times With Time zones
date_default_timezone_set('America/New_York');
$datetime = new DateTime('2000-12-31 23:59:59');
// output: 2000-12-31 23:59:59 America/New_York
echo $datetime->format('Y-m-d H:i:s e').PHP_EOL;
// output: 2000-12-31 23:59:59 EST
echo $datetime->format('Y-m-d H:i:s T').PHP_EOL;
// output: 2000-12-31 23:59:59 -0500
echo $datetime->format('Y-m-d H:i:s O').PHP_EOL;
3. How do I get the difference between 2 times?
It is common to need to know the difference in time between 2 dates/times. With DateTime there are actually 3 different ways to achieve this, and which one you will want to use will depend on your needs.
How (with Examples)
Scenario 1: You only need to know if $datetime1 is greater than, less than, or equal to $datetime2
In this case, you can simply directly compare the instances of DateTime.
$datetime1 = new DateTime;
sleep(1);
$datetime2 = new DateTime;
var_dump($datetime1 > $datetime2); // FALSE
var_dump($datetime1 < $datetime2); // TRUE
var_dump($datetime1 == $datetime2); // FALSE
Scenario 2: You need the difference between $datetime1 and $datetime2 expressed as broken-down years/months/days/etc.
This will work for most cases, however the DateInterval instance you get back from $datetime->diff() has its own "gotchas" and may not work for your specific use case.
$datetime1 = new DateTime('2000-01-01 00:00:00.000000');
$datetime2 = new DateTime('2001-02-03 04:05:06.789012');
$diff = $datetime1->diff($datetime2);
// output: 1 Years, 1 Months, 2 Days, 4 Hours, 5 Minutes, 6 Seconds
echo $diff->format('%y Years, %m Months, %d Days, %h Hours, %i Minutes, %s Seconds');
Scenario 3: You need the difference between $datetime1 and $datetime2 expressed in another way.
This will work in any context at the cost of a little extra code.
$interval = 60 * 60 * 24; // 1 day in seconds
$datetime1 = new DateTime('2000-01-01');
$datetime2 = new DateTime;
$diff = $datetime2->getTimestamp() - $datetime1->getTimestamp();
// output: It has been 6956 days since 2000-01-01!
printf('It has been %s days since %s!', floor($diff / $interval), $datetime1->format('Y-m-d'));
4. How do I account for time zones?
When it comes to dealing with time in programming, by far the worst part is dealing with time zones. Fortunately, this is something else that the DateTime class handles gracefully.
How
DateTime's constructor allows you to specify the source time zone in either the date/time string or as the 2nd Argument. After that, just set a new timezone with $datetime->setTimezone() and DateTime will take care of the rest.
// These 2 lines are functionally identical
$datetime = new DateTime('2001-01-01 00:00:00', new DateTimeZone('UTC')); // recommended, may be faster
$datetime = new DateTime('2001-01-01 00:00:00 UTC');
$datetime->setTimezone(new DateTimeZone('EST'));
I recommend checking out the full list of PHP's supported time zones as well as the docs on the DateTimeZone class.
Example
Lets say you want to show your end-users the time your customer support line opens in their time zone. With DateTime the code would look something like this:
$support_opens = new DateTime('08:00:00', new DateTimeZone('America/New_York'));
$customer_timezones = array('America/New_York', 'America/Chicago', 'America/Denver', 'America/Phoenix', 'America/Los_Angeles', 'America/Anchorage', 'America/Adak', 'Pacific/Honolulu');
echo "Today we open at the following times:".PHP_EOL;
foreach ($customer_timezones as $timezone) {
$support_opens->setTimezone(new DateTimeZone($timezone));
echo '* '.$support_opens->format('g:ia \f\o\r \t\h\e e').' time zone'.PHP_EOL;
}
Output:
Today we open at the following times:
* 8:00am for the America/New_York time zone
* 7:00am for the America/Chicago time zone
* 6:00am for the America/Denver time zone
* 6:00am for the America/Phoenix time zone
* 5:00am for the America/Los_Angeles time zone
* 4:00am for the America/Anchorage time zone
* 3:00am for the America/Adak time zone
* 3:00am for the Pacific/Honolulu time zone
Notice: If you supply a time zone in both the date/time string and as the second argument, the argument time zone will be ignored.
$datetime = new DateTime('2001-01-01 00:00:00 EST', new DateTimeZone('UTC'));
// output: 2001-01-01 00:00:00 EST
echo $datetime1->format('Y-m-d H:i:s');
I have been using DateTime Diff (in php) to get various settings for pairs of dates - two formatted dates to display, a difference from the date to now (eg "start date was 3 months 2 days ago"), and a length between the two dates ("length is 2 months 3 days").
The problem is that DateTime Diff ignores one of the days so if the start is yesterday and the end is tomorrow, it gives 2 days whereas I want 3 because both dates should be included in the length. If it was just days, I could simply add 1 to the result, but I wanted to use the years/months/days results from the Diff and these are determined at construct.
The only way I have found to get the desired results is to create a DateTime for start and end (to get the formatted dates and the differences). Then take the end DateTime, add 1 day to it, then work out the length.
It's a bit clunky but there seems to be no way to tell DateTime Diff to include both start and end dates in the result.
DateTime encapsulates a specific moment in time. "yesterday" is not a moment but a time range. The same for "tomorrow".
DateTime::diff() doesn't ignore anything; it just provides you the exact difference (in day, hours, minutes a.s.o.) between two moments in time.
If you want to get the diff between "tomorrow" and "yesterday" as "3 days" you can subtract the first second of "yesterday" from (one second after the last second of "tomorrow").
Like this:
// Always set the timezone of your DateTime objects to avoid troubles
$tz = new DateTimeZone('Europe/Bucharest');
// Some random time yesterday
$date1 = new DateTime('2016-07-08 21:30:15', $tz);
// Other random time tomorrow
$date2 = new DateTime('2016-07-10 12:34:56', $tz);
// Don't mess with $date1 and $date2;
// clone them and do whatever you want with the clones
$yesterday = clone $date1;
$yesterday->setTime(0, 0, 0); // first second of yesterday (the midnight)
$tomorrow = clone $date2;
$tomorrow->setTime(23, 59, 59) // last second of tomorrow
->add(new DateInterval('PT1S')); // one second
// Get the difference; it is the number of days between and including $date1 and $date2
$diff = $tomorrow->diff($yesterday);
printf("There are %d days between %s and %s (including the start and end date).\n",
$diff->days, $date1->format('Y-m-d'), $date2->format('Y-m-d')
);
How to calulate Future date.
Today date is : 2015-09-05
if day is 120, then what will be the, future date.
I was creating Program in php, which user pay Online,
We will give validity date by 120days from paid amount date.
Then what will be the validity date.
I will accept that person answer me correct answer 1st
The following will get you the date 120 days into the future:
strtotime("+120 days");
The strtotime function also takes a second parameter, which can be used if you want to add 120 days to a specific date instead of to the current date.
See the official documentation for more information.
$expirydate = date('Y-m-d G:i:s', strtotime('+120 days'));
'time()' will give you unix timestamp (miliseconds elapsed since 1.1.1970).
120 days in miliseconds can be calculated like this '120*24*60*60'.
You can get current date by 'date($format)' and then add offset to it 'date($format, $offset)'.
Here is an example:
<?php
$future = time() + (120*24*60*60);
$format = "Y-m-d";
$now = date($format);
$future_date = date($format, $future);
?>
You can also check similar example here
I am using PHP and MySQL, and want to calculate date time difference between two datetimes. I have a message table, in that table createdate is one field. I want to find out day and time difference from current date in the format 1 day 2 hours ago. What is the best way to go about this?
Use PHP's built in date functions:
<?php
$start_time = "Y-m-d H:i:s"; // fill this in with actual time in this format
$end_time = "Y-m-d H:i:s"; // fill this in with actual time in this format
// both of the above formats are the same as what MySQL stores its
// DATETIMEs in
$start = new DateTime($start_time);
$interval = $start->diff(new DateTime($end_time));
echo $interval->format("d \d\a\y\s h \h\o\u\r\s");
DateInterval documentation
DateTime::diff documentation
SELECT TIMESTAMPDIFF(HOUR,createdate,NOW()) as diff_in_hours FROM table1;
Then on php side you can easily convert the value of diff_in_hours to days + hours format.
You can use DATEDIFF() and TIMEDIFF() functions in MySQL.
SELECT DATEDIFF(CURDATE(), createdate) AS output_day,
TIMEDIFF(CURDATE(), createdate) AS output_time
FROM message_table
For output_day it is already in day unit. But output_time require additional manipulation to get the hour part of the time difference.
Hope this helps.