I'm trying to calculate the difference between 2 dates: $now and $old to get -> how long as past since old datetime.
$current_date = time();
$old= new DateTime($dateTimeString);
$now= new DateTime($current_date);
$interval = $now->diff($old);
I was trying with these values: 2016-02-23 02:15:43 --- 2016-02-22 21:45:11 and the result was more than 14hours of difference. I print the result like this:
$interval->format('%i Hours ago.');
$interval->format('%d Days ago.');
What I am doing wrong please?
The problem is here:
$current_date = time();
$now = new DateTime($current_date);
The value returned by time() is the number of seconds since 1970-01-01 00:00:00 UTC. The DateTime constructor tries to interpret it as a date that uses one of the usual date formats, it fails and produces a DateTime objects initialized with 0 (i.e. 1970-01-01 00:00:00 UTC).
If you want to create a new DateTime object from an Unix timestamp (the value returned by time() you can use DateTime::createFromFormat()
$current_time = time();
$now = DateTime::createFromFormat('U', $current_time);
Or you can pass the timestamp prefixed with '#' to DateTime::__construct():
$current_time = time();
$now = new DateTime('#'.$current_time);
This format is explained in the Compound date/time formats page.
But the easiest way to create a DateTime object that contains the current date and time is to either pass 'now' as argument to the constructor or omit it altogether:
$now1 = new DateTime('now');
$now2 = new DateTime();
The two DateTime objects constructed above should be identical (there is a small chance they are 1-second apart, though) and they both must contain the current date & time.
Related
I have a date in UTC / Epoch format from a mongo database (1659052800000) and I'm trying to convert it to a friendly format using PHP for the PST timezone.
Here's what I've tried.
date_default_timezone_set('PST');
$this->vars[dateOfEvent] = date('Y-m-d', 1659052800000);
and
date_default_timezone_set('PST');
$dt = new DateTime(1659052800000);
$this->vars[dateOfEvent] = $dt->format('Y-m-d');
but neither give me the correct date. I'm expecting it to out "2022-07-28"
You can set the timezone temporarily for the DateTime object. Also you need to set timestamp divided by 1000 or remove the last three zeroes.
$dt = new DateTime();
$dt->setTimestamp(1659052800000 / 1000);
$dt->setTimezone(new DateTimeZone('PST'));
echo $dt->format('Y-m-d');
prints
2022-07-28
I have two Datetimes like this (the dates being actually $vars)
$startTime = \DateTime::createFromFormat('Y/m/d H:i', '2015/01/01 23:00');
$endTime = \DateTime::createFromFormat('Y/m/d H:i', '2015/01/02 01:00');
I struggle with a (possibly pretty) simple problem: How could I determine if the two dates are on different calendar days?
I cannot do < as 2015/01/01 22:00 < 2015/01/01 23:00 would also be true. I can also not do this:
$diff = $startTime->diff($endTime);
$days = $diff->format('%d');
echo $days;
as it gives me 0.
THIS gives me an idea about how to do it, but for javascript, what would be the equivalent for php?
//UPDATE
$startDate = $startTime->format('Y/m/d');
$endDate = $endTime->format('Y/m/d');
$diffDates = $startDate->diff($endDate);
$daysDiff = $diffDates->format('%d');
echo $daysDiff;
I think that might be the right approach now, thanks to the comments, but now I get Error: Call to a member function diff() on string
//UPDATE FOR CLARIFICATION WHAT I'M TRYING TO DO
I just want to have the difference in days, so for the above it would be '1' (although only 2 hours difference actually) and for example '2015/01/01 23:00' and '2015/01/03 17:00' would be '2'.
Just create the dates with time set to 00:00:00:
$startTime = \DateTime::createFromFormat('Y/m/d H:i:s', '2015/01/01 00:00:00');
$endTime = \DateTime::createFromFormat('Y/m/d H:i:s', '2015/01/02 00:00:00');
or reset time to zero on existing dates:
$startTime->setTime(0, 0, 0);
$endTime->setTime(0, 0, 0);
then it should work:
$diff = $startTime->diff($endTime);
$days = $diff->format('%d');
echo $days; // 1
Bonus
If you want to work only with dates, remember to set the time to 00:00:00 in createFromFormat or reset it with setTime. If you won't provide time in createFromFormat PHP will set it to the current time:
$date = DateTime::createFromFormat('Y-m-d', '2016-01-21');
print $date->format('H:i:s'); //not 00:00:00
To fix it, you must either:
provide 00:00:00 time in format:
$date = DateTime::createFromFormat('Y-m-d H:i:s', '2016-01-21 00:00:00');
prefix the date format with exclamation mark and omit the time, this will set the time to 00:00:00 automatically:
$date = DateTime::createFromFormat('!Y-m-d', '2016-01-21');
reset the time after creation:
$date = DateTime::createFromFormat('Y-m-d', '2016-01-21');
$date->setTime(0, 0);
I think this is one of the few situations where the use of strings for date calculations is justified:
function onDifferentDays(\DateTimeInterface $startTime, \DateTimeInterface $endTime){
return $startTime->format('Y-m-d')!==$endTime->format('Y-m-d');
}
This code should be easy to extend to include time zone.
There're other alternatives but I don't think they're normally worth the effort:
Compare element by element (day, month and year):
The PHP DateTime class doesn't offer dedicated functions, only format().
Normalize both dates to a common time and compare with == (not ===):
Unless you're using immutable objects you need to clone input or expect side effects
You also need to ensure that time exists in the active time zone though midnight is probably safe enough.
Whatever, YMMV ;-)
Comparing formatted dates is the right thing to do:
$a->format('Y-m-d') === $b->format('Y-m-d')
There is a method for that if you use Carbon:
$dt1->isSameDay($dt2)
So I recommend to use it instead of previous answers given here.
http://carbondoc/docs/#api-comparison
I have tried to solve it by extracting the numeric part and then parsed it using date function. But it shows me some old date which I guess is not correct.
$datef = "1490914800000+0100";
$adada = date('Y-m-d H:i:s', $datef);
// Gives date 1987-10-13 18:31:28 which is an old date. Please suggest.
One approach, well-covered by this SO question, is to use the DateTime() function to convert time in seconds since epoch to a date, and then display this date using format(). But there are two caveats with your data. First, you appear to have milliseconds since the epoch, which needs to be converted to seconds. Second, you also have a timezone shift, in hours, tagged to the end. I split your $datef string into two parts, epoch and timezone, then arrive at the number of seconds since epoch.
list($epoch, $timezone) = explode('+', $datef);
$epoch = ($epoch / 1000) + (substr($timezone, 0, 2)*60*60) +
(substr($timezone, 2, 2)*60);
$dt = new DateTime("#$epoch");
echo $dt->format('Y-m-d H:i:s');
Output:
2017-03-31 00:00:00
Demo here:
PHP Sandbox
The time seems to be in milliseconds.
You can add the timezone shift to the seconds. 1 hour = 3600 seconds.
$milliSeconds = intval("1490914800000");
$seconds = $milliSeconds/1000;
$date = date("Y-m-d H:i:s", $seconds);
I have two Datetimes like this (the dates being actually $vars)
$startTime = \DateTime::createFromFormat('Y/m/d H:i', '2015/01/01 23:00');
$endTime = \DateTime::createFromFormat('Y/m/d H:i', '2015/01/02 01:00');
I struggle with a (possibly pretty) simple problem: How could I determine if the two dates are on different calendar days?
I cannot do < as 2015/01/01 22:00 < 2015/01/01 23:00 would also be true. I can also not do this:
$diff = $startTime->diff($endTime);
$days = $diff->format('%d');
echo $days;
as it gives me 0.
THIS gives me an idea about how to do it, but for javascript, what would be the equivalent for php?
//UPDATE
$startDate = $startTime->format('Y/m/d');
$endDate = $endTime->format('Y/m/d');
$diffDates = $startDate->diff($endDate);
$daysDiff = $diffDates->format('%d');
echo $daysDiff;
I think that might be the right approach now, thanks to the comments, but now I get Error: Call to a member function diff() on string
//UPDATE FOR CLARIFICATION WHAT I'M TRYING TO DO
I just want to have the difference in days, so for the above it would be '1' (although only 2 hours difference actually) and for example '2015/01/01 23:00' and '2015/01/03 17:00' would be '2'.
Just create the dates with time set to 00:00:00:
$startTime = \DateTime::createFromFormat('Y/m/d H:i:s', '2015/01/01 00:00:00');
$endTime = \DateTime::createFromFormat('Y/m/d H:i:s', '2015/01/02 00:00:00');
or reset time to zero on existing dates:
$startTime->setTime(0, 0, 0);
$endTime->setTime(0, 0, 0);
then it should work:
$diff = $startTime->diff($endTime);
$days = $diff->format('%d');
echo $days; // 1
Bonus
If you want to work only with dates, remember to set the time to 00:00:00 in createFromFormat or reset it with setTime. If you won't provide time in createFromFormat PHP will set it to the current time:
$date = DateTime::createFromFormat('Y-m-d', '2016-01-21');
print $date->format('H:i:s'); //not 00:00:00
To fix it, you must either:
provide 00:00:00 time in format:
$date = DateTime::createFromFormat('Y-m-d H:i:s', '2016-01-21 00:00:00');
prefix the date format with exclamation mark and omit the time, this will set the time to 00:00:00 automatically:
$date = DateTime::createFromFormat('!Y-m-d', '2016-01-21');
reset the time after creation:
$date = DateTime::createFromFormat('Y-m-d', '2016-01-21');
$date->setTime(0, 0);
I think this is one of the few situations where the use of strings for date calculations is justified:
function onDifferentDays(\DateTimeInterface $startTime, \DateTimeInterface $endTime){
return $startTime->format('Y-m-d')!==$endTime->format('Y-m-d');
}
This code should be easy to extend to include time zone.
There're other alternatives but I don't think they're normally worth the effort:
Compare element by element (day, month and year):
The PHP DateTime class doesn't offer dedicated functions, only format().
Normalize both dates to a common time and compare with == (not ===):
Unless you're using immutable objects you need to clone input or expect side effects
You also need to ensure that time exists in the active time zone though midnight is probably safe enough.
Whatever, YMMV ;-)
Comparing formatted dates is the right thing to do:
$a->format('Y-m-d') === $b->format('Y-m-d')
There is a method for that if you use Carbon:
$dt1->isSameDay($dt2)
So I recommend to use it instead of previous answers given here.
http://carbondoc/docs/#api-comparison
The server that I have my sited hosted is on PHP5.12.14, and I have an error when I run the DateTime object from PHP5.3
# DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
$date = new DateTime($item_user['mem_updated']);
# add a day to the object
$date -> add(new DateInterval('P1D'));
the error,
Fatal error: Call to undefined method DateTime::add() in /homepages/xxx.php on line xx
So, I have look for the other solutions rather than sticking to PHP5.3's DateTime object. How can I write the code to replace the code above?
basically I have this date and time data (for instance - 2011-01-21 02:08:39) from the mysql database, and I just need to add 1 day or 24 hours to that date/time, then passing it into a function below,
$time_togo = time_togo($date -> format('Y-m-d H:i:s'));
thanks.
strtotime would work
$timestamp = strtotime($item_user['mem_updated']);
$time_togo = date("Y-m=d H:i:s", strtotime("+1 Day", $timestamp));
Here's an example:
$date = date('Y-m-d H:i:s');
$new_tstamp = strtotime($date.'+1WEEK');
$new_date = date('Y-m-d H:i:s', $new_tstamp);
In other words, strtotime lets you use date expressions like +1DAY, +1MONTH and so on.
The above will work for date string (e.g.: 2010-01-01). If your original date is a Unix timestamp, you can still use strtotime, although a bit differently:
$new_tstamp = strtotime('+1WEEK', $timestamp);