I have an input file with type time. what I want to do is to get time from the moment now that is if time right now is 2019-11-26 23:50:00 and the value of input field if 22:30:00, I should get a date 2019-11-27 22:30:00.
How can achieve this in PHP? in short, get the datetime stamp for the next occurrence of 22:30:00 which is 2019-11-27 22:30:00 as per the given example.
answer found but can we optimize the code more ?
$a = explode(':', date('H:i:s', strtotime($validateData['time'])));
$str = '+'.$a[0].' hours '.$a[1].' minutes '.$a[2].' seconds';
$trigger_at = date(date('Y-m-d H:i:s', strtotime( $str, strtotime($validateData['date']))));
return $trigger_at;
This is simpler and a lot more readable
$time = "21:30:00"; // Time from input
$today = date("Y-m-d $time");
$tomorrow = date("Y-m-d H:i:s", strtotime($today)+86400);
$date = strtotime($today) < strtotime("now") ? $tomorrow : $today;
Explanation: We take timestamp at specified hour for today and tomorrow, if today timestamp has been passed, we use tomorrow timestamp. Simple. :)
All you are doing is appending (concatenating) a string onto another string.
$time = "22:30:00"; // This is the time you have
$date = date("Y-m-d"); // Right now in yyyy-mm-dd format.
$newdatetime = $date.' '.$time;
That will give you the current date with the supplied time appended to it. You can convert that back into a timestamp using:
$timestamp = strtotime($newdatetime);
The answer below is based on the original question in which the time was assumed to be an offset from now. It is left here simply to avoid deleting a lot of code.
The function strtotime is easy to use for that. However, it doesn't accept HH:MM:SS format. So, you have to alter the string. I would do it like:
$time = "22:30:00"; // This is the time you have
$a = explode(':', $time);
$str = '+'.$a[0].' hours '.$a[1].' minutes '.$a[2].' seconds'; // This breaks it into separate numbers with labels.
$date = date("Y-m-d h:i:s", strtotime($str)); // The adjusted date
You can change the format of the output as you like by changing the first string used in the date function.
Related
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 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)
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 want to add time to an existing date. I have 2 string variables:
$date = "2013-01-05 10:55:15";
$interval = "50:25:10";
I want to calculate the final date "2013-01-07 13:20:25". The hours in time can be bigger than 23, meaning that this interval can be greater than a whole day.
What's the best way to do this ?
Use DateTime API:
$date = new DateTime("2013-01-05 10:55:15");
$date->add(new DateInterval("PT50H25M10S"));
then you can convert it back to string with the same date format you would use with date() function, if you want to:
$string = $date->format("Y-m-d H:i:s");
For more information about the DateInterval definition, visit this page:
DateInterval
The format starts with the letter P, for "period." Each duration
period is represented by an integer value followed by a period
designator. If the duration contains time elements, that portion of
the specification is preceded by the letter T.
Here are some simple examples. Two days is P2D. Two seconds is PT2S.
Six years and five minutes is P6YT5M.
so in this case PT50H25M10S means 50 hours, 25 minutes, and 10 seconds
Note that DateInterval is available only since PHP 5.3, if you have to use lower version, you could use something like this:
$time = strtotime("2013-01-05 10:55:15");
$time += 55*60*60 + 25*60 + 10;
$newDate = date("Y-m-d H:i:s");
This is a little tricky.
Normally what you would do here if it was a static period, or was a single period type, is something along the lines of:
$date = "2013-01-05 10:55:15";
$time = new DateTime($date);
$time->add(new DateInterval('PT5M'));
This would add 5 minutes to the datetime. However I doubt you can pass the whole interval in. So what you'll probably have to do is split the interval by : and then add each part of the interval (I assume it is dynamic?) to the date separately. So first hours, then minutes, then seconds
For more on this, see here: http://www.php.net/manual/en/datetime.add.php
You could first explode the interval and then get the hours, minutes, seconds, and then use DateTime's add() to add the interval, like so:
$interval = '50:25:10';
$datestring = '2013-01-05 10:55:15';
list($hours, $minutes, $seconds) = explode(':', $interval);
$date = new DateTime($datestring);
$date->add(new DateInterval('PT'.$hours.'H'.$minutes.'M'.$seconds.'S'));
echo $date->format('Y-m-d H:i:s');
Demo!
Use a DateInterval and DateTime->add():
$date = new DateTime("2013-01-05 10:55:15");
$date->add(new DateInterval("PT50H25M10S"));
In case anyone needs based on answers above, I made my function like this:
public function addTime($date, $time) {
$atime = explode(":", $time);
$_date = date_create_from_format("Y-m-d H:i:s", $date);
$_date->add(new DateInterval("PT" . intval($atime[0])."H".intval($atime[1])."M".intval($atime[2])."S"));
return $_date->format("Y-m-d H:i:s");
}
hope it helps someone
hello i am working with the Date() function i am getting a time that is current and time that is coming from a database to compare the times, but the dates are different:
date_default_timezone_set("America/Los_Angeles"); // set time zone to LA
$date = date("m-d-Y h:i:s"); // current time
$current_time = strtotime($date); // current time in seconds
$get_time = 1357487529; //linux time from the server
$difference = $current_time - $get_time; //seconds that have pass already
$get_date = date("m-d-Y h:i:s", $get_time); // convert the linux time to current time and date
$exploded_get_date = explode(" ", $get_date); //divide the get date into 2 parts by space 0 = date 1 = time
$exploded_current_date = explode(" ", $date); //divide the current date into 2 parts by space 0 = date 1 = time
the results i get are:
01-Sun-2013 07:52:09 //get date
06-01-2013 07:56:25 //current date
1357487785 // current time
1357487529 // get time
256 //difference
why is it saying i have month 1 in the get date, but in the current date is actually month 6 and also the day it says it is Sunday 6, when is Saturday 1? how can i fix this?
m-d-Y is NOT a valid format for parsing. Only you Americans think it's sensible to put the elements in an unsorted order...
Anyway, the point is, what does 06-01-2013 mean? Is it June 1st, or January 6th?
For consistency's sake, the computer assumes January 6th (d-m-Y format).
I would strongly recommend using the Y-m-d H:i:s format, as this is inherently sortable as string due to being fully big-endian.
EDIT: It should be noted that you can just use time() to get the current timestamp.
Your code is VERY redundant:
$date = date("m-d-Y h:i:s"); // current time
$current_time = strtotime($date); // current time in seconds
can be replaced with a simple
$current_time = time();
and
$get_date = date("m-d-Y h:i:s", $get_time); // convert the linux time to current time and date
$exploded_get_date = explode(" ", $get_date); //divide the get date into 2 parts by space 0 = date 1 = time
$exploded_current_date = explode(" ", $date);
could just be
$exploded_date = date('m-d-y', $get_time);
$exploded_time = date('h:i:s', $get_time);
You are wasting a considerable amount of CPU cycles on useless/repetitive and ultimately redundant operations.
And in the greater picture, your error is that PHP's normal and easiest analysed/parsed date/time strings are in yyyy-mm-dd format. You're building mm-dd-yyyy, which is pretty much entirely scrambled. PHP cannot guess properly when you feed it uncertain formats. That means strtotime() is going to screw up and give you incorrect results.