PHP: Alternative to DateTime - php

I cannot use DateTime because of the version of PHP I am running. Can anyone suggest a way to get the equivalent value using strToTime or some other date function. I know this is probably an easy question but I am very rusty on dates in php.
i.e. something like
$date = strToTime('today');
where $date is a date that I can then manipulate by adding hours and so forth along these lines...
$start = $date->format('Y-m-d H:i:s');
$date->modify('+ 60 minutes');
$end = $date->format('Y-m-d H:i:s');
Thanks in advance for any suggestions.

$startTime = strtotime('now');
$endTime = strtotime('+60 minutes', $startTime);
$start = date('Y-m-d H:i:s', $startTime);
$end = date('Y-m-d H:i:s', $endTime);
You can pass a 2nd parameter to strtotime that will be the time that is used when the calculation is made. By default it is time().
strtotime

There are alternatives, that you can get from github, just type php date in search.
For example, you can use moment.php library, which is a clone of moment.js library which is intented to fix problems among different systems, versions etc...
And to perform date calc in moment.php
For example
$m = new \Moment\Moment('2012-05-15T12:30:00', 'CET');
echo $m->addMinutes(60)->format(); // 2012-05-08T13:15:00+0200

Related

Check with Carbon if a date is on a different day [duplicate]

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

Difference between timestamps in minutes in PHP

I want to get difference between 2 timestamps of format Y-m-d H:i:s in minutes in PHP.
The code used is,
$currentDate = date('Y-m-d H:i:s');
$userLastActivity = date($date);
$timeLapse = (($currentDate - $userLastActivity)/60);
Here, $date is obtained from database.
The value of $timeLapse is 0 in output. Please help.
Try using unix timestamp. Practically it measures the time in seconds from 1/1/1970 and it's a lot easier to use and understand than a php object.
$currentTimestamp = new DateTime()->getTimestamp();
$userLastActivity = date($date)->getTimestamp();
$timeLapse = (($currentDate - $userLastActivity)/60);
You should have the time saved as timestamp on the server too, in that case you could use the $date directly as a number, with no need for a conversion. And also, because it's universal, you can pass it around to javascript or any other language without any worries for conversion
Use strtotime to parse textual datetime into a Unix timestamp and substract $userLastActivity from $currentDate and divide by 60.
See if this helps -
<?php
$currentDate = strtotime(date('Y-m-d H:i:s'));
$date = "2016-10-11 02:40:50";
$userLastActivity = strtotime($date);
echo round(abs($currentDate - $userLastActivity) / 60). " minutes";
?>
For more details :strtotime
Change these 2 lines for a start, as I don't think dividing dates by 60 is gonna work to well.
$currentDate = time();
$userLastActivity = strtotime($date);
That way you have time stamps and not dates (string)

PHP check if two Datetimes are not on the same calendar day

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

Setting Php and Mysql timestamp

I need to set timestamp eg. 4 hours ahead and 2 hours ahead separately
In my database, I have their columns as timestamp.
I know I could do something similar to this but am not sure if it's correct.
// For 4 hours ahead of time
$dt2 = date("Y-m-d 04:i:s");
//For 2 days ahead
$dt2 = date("Y-m-02 H:i:s");
//For 4 hours ahead of time
$dt2 = date("Y-m-d H:i:s", strtotime('+4 hours'));
//For 2 days ahead of time
$dt2 = date("Y-m-d H:i:s", strtotime('+2 days'));
In my mind it's much better to work with DateTime field and the DateTime class.
You have the ability so modify that objects very easily. For example:
$aktDate = new \DateTime();
Now you have the actual date and time in an object. If you want you can put a string insight the DateTime function so set your date manually.
$aktDate = new \DateTime('Y-m-d 04:i:s');
Not you can modify your dates if you want with the modify function.
in your case:
$pastDate = clone $aktDate;
$pastDate->modify('+2 days');
$futureDate = clone $aktDate;
$futureDate->modify('+4 days');
if($pastDate < $aktDate && $aktDate < $futureDate) {
// do something
}
I like the DateTime function much more because it's readable and you can work directly with your DateTime fields from your MySQL database if you have such fields. You can write that example much shorter but so you have better readability.
$date = new DateTime('now');
$date->modify('+2 days');
echo $date->format('Y-m-d H:i:s');
$date = new DateTime('now');
$date->modify('+4 hours');
echo $date->format('Y-m-d H:i:s');
You need to use the strtotime() function (http://php.net/manual/en/function.strtotime.php).
For your examples:
//+2 hours<br>
strtotime("+2 hours");
// +2 days<br>
strtotime("+2 days")
Edit: for what you ask, about posted values, the syntax is like this:
strtotime("+2".$_POST['field_name']." days");
You can use hours/days/months/weeks/years and either + or -

get strtotime of specific time in php

I want to get the timestamp of a day/time for eg
17/12/2014 8pm
Currently I am doing
$curtime = strtotime(date("Y-m-d H:i:s"));
which is giving me the current timestamp but I need to be of 8pm.
Any help is highly appreciated. Thanks in advance.
If you're trying to get a timestamp of today at 8pm, it's actually much more simple than using date since you can use relative times in a strtotime:
$curtime = strtotime('today 8pm');
If you test this with date:
echo date('Y-m-d H:i:s', $curtime); // Returns 2014-12-17 20:00:00
Here's a whole writeup on relative date formats that explains how you can construct proper relative dates.
The best way to do this is using date_create_from_format. Checking out format's parameters, you will end up with something like this:
$date = date_create_from_format('d/m/Y ga', '17/12/2014 8pm');
if (!empty($date)) {//returns false if can't create date
$timestamp = $date->getTimestamp();
//echo date('d/m/Y H:i:s', $timestamp);
}

Categories