How many seconds from midnight until specific Datetime - php

Is there a nice simple shorthand way of finding out how many seconds past midnight a certain datetime is? Not how many seconds it is away from now, the seconds past in that day
eg:
2015-04-10 00:00:00 should returns 0
2015-04-12 09:20:00 should returns 33600
2015-04-14 15:20:00 should returns 55200
Is there a nice short method of doing this?

Here is a simple code for you.
Any day code
<?php
$date = "2015-04-12 09:20:00";
$midnight = strtotime(date("Y-m-d 00:00:00", strtotime($date)));
$now = strtotime($date);
$diff = $now - $midnight;
echo $diff;
?>
Current day code
<?php
$midnight = strtotime("midnight");
$now = date('U');
$diff = $now - $midnight;
echo $diff;
?>
Maybe a more clean code would be to use strtotime("midnight", <EpochTime>);
<?php
$date = "2015-04-12 09:20:00";
$midnight = strtotime("midnight", strtotime($date));
$now = strtotime($date);
$diff = $now - $midnight;
echo $diff;
?>

A day is 24 hours is 60 minutes is 60 seconds is 1000 miliseconds, so timestamp % (24*60*60*1000) could work, maybe, at least if you are on the same time zone as the epoch php is using (or whatever you timestamp is coming from). It would work at least for nothing too demanding of accuracy. PHP uses your system's time, so many things will break the idea (change the clock, DST, leap seconds, etc)
I would personally use timestamp - startofday timestamp and calculate using the language's calendar instead.

Related

How to check how many days passed from timestamp - counting the days at midnight

I'm trying to know how many days have passed from a certain timestamp, but the problem is I can't set it up, so that after midnight will count it as another day.
Here is what I tried:
<?php
$now = time(); // or your date as well
$your_date = 1572123244;
$datediff = $now - $your_date;
echo round($datediff / (60 * 60 * 24));
If I put a timestamp of five minutes before midnight (1572134100), five minutes after midnight should appear that "one day passed"
The usual way of counting the days passed since a given timestamp would be something like this:
$dt = date_create_from_format('U', 1572046200);
$diff = $dt->diff(new DateTime());
echo $diff->days;
But this counts the full 24 hour periods as days. In your case you want to count calendar dates irrespective of the time of day. I would recommend then to ceil the timestamp to the midnight.
$dt = date_create_from_format('U', 1572047700);
$dt->setTime(0, 0); // set time to 00:00
$now = new DateTime('now', new DateTimeZone('UTC')); // time now, but in UTC
$now->setTime(0, 0); // set time to 00:00
$diff = $dt->diff($now);
echo $diff->days;
I am not sure about your current time zone, but timestamps are by nature in UTC, hence you should probably normalize your local time to UTC as well.
What this code does is it sets both today's date and the timestamp you are comparing against to the midnight of the UTC day and then calculates the difference between the two. Taking the time out of equation, this will always count the full 24 hour days.

hh:mm:ss difference return wrong answer in php

I am using this code to calculate the time period. In fact, I want the period between two HH:MM:SS moment and have a result in HH:MM:SS format.
$time1 = strtotime('00:00:00');
$time2 = strtotime('00:00:07');
$diff = $time2 - $time1;
$diff = date('H:i:s', $diff);
I'm expecting 00:00:07 but I get 01:00:07. What could be the problem?
Irvin run here, and get right answer but I run the same code on my local machine and wrong!!
Is it timezone or maybe some configuration effect the result?!
Please stop using strtotime and date functions. Use the DateTime class.
And if you would have searched better, finding difference for two dates has already been all over SO. For instance, my answer here. Slightly changed it would look like:
$create_time = "00:00:00";
$current_time="00:00:07";
$dtCurrent = DateTime::createFromFormat('H:i:s', $current_time);
$dtCreate = DateTime::createFromFormat('H:i:s', $create_time);
$diff = $dtCurrent->diff($dtCreate);
echo $diff->format("%H:%I:%S"); // to get HH:MM:SS format
This returns 00:00:07
See DateInterval::format for more formatting details.
It's because when you minus time 1 from time 2 you end up with 7;
The date function needs a timestamp, 7 is not a timestamp.
You could use http://php.net/manual/en/datetime.diff.php to calculate the difference instead?
You should consider the UNIX epoch which cancels timezone diffrences in ini settings, essentially. it's Jan 1st '70. You can check your server/app's setup for timezone by adding e, O or P. Check this code:
$time1 = strtotime('00:00:00 +0000');
$time2 = strtotime('00:00:07 +0000');
$epoch = strtotime('01 Jan 1970');
$diff = $time2 - $time1;
var_dump($time1,$time2,$epoch,$diff);
$diff = date('H:i:s', $epoch+$diff);
echo $diff;

Given a Unix timestamp, how to get beginning and end of that day?

I have a Unix timestamp like this:
$timestamp=1330581600
How do I get the beginning of the day and the end of the day for that timestamp?
e.g.
$beginOfDay = Start of Timestamp's Day
$endOfDay = End of Timestamp's Day
I tried this:
$endOfDay = $timestamp + (60 * 60 * 23);
But I don't think it'll work because the timestamp itself isn't the exact beginning of the day.
strtotime can be used to to quickly chop off the hour/minutes/seconds
$beginOfDay = strtotime("today", $timestamp);
$endOfDay = strtotime("tomorrow", $beginOfDay) - 1;
DateTime can also be used, though requires a few extra steps to get from a long timestamp
$dtNow = new DateTime();
// Set a non-default timezone if needed
$dtNow->setTimezone(new DateTimeZone('Pacific/Chatham'));
$dtNow->setTimestamp($timestamp);
$beginOfDay = clone $dtNow;
$beginOfDay->modify('today');
$endOfDay = clone $beginOfDay;
$endOfDay->modify('tomorrow');
// adjust from the start of next day to the end of the day,
// per original question
// Decremented the second as a long timestamp rather than the
// DateTime object, due to oddities around modifying
// into skipped hours of day-lights-saving.
$endOfDateTimestamp = $endOfDay->getTimestamp();
$endOfDay->setTimestamp($endOfDateTimestamp - 1);
var_dump(
array(
'time ' => $dtNow->format('Y-m-d H:i:s e'),
'start' => $beginOfDay->format('Y-m-d H:i:s e'),
'end ' => $endOfDay->format('Y-m-d H:i:s e'),
)
);
With the addition of extended time in PHP7, there is potential to miss a second if using $now <= $end checking with this.
Using $now < $nextStart checking would avoid that gap, in addition to the oddities around subtracting seconds and daylight savings in PHP's time handling.
Just DateTime
$beginOfDay = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($timestamp)->format('Y-m-d 00:00:00'))->getTimestamp();
$endOfDay = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($timestamp)->format('Y-m-d 23:59:59'))->getTimestamp();
First a DateTime object is created and the timestamp is set to the desired timestamp. Then the object is formatted as a string setting the hour/minute/second to the beginning or end of the day. Lastly, a new DateTime object is created from this string and the timestamp is retrieved.
Readable
$dateTimeObject = new DateTime();
$dateTimeObject->setTimestamp($timestamp);
$beginOfDayString = $dateTimeObject->format('Y-m-d 00:00:00');
$beginOfDayObject = DateTime::createFromFormat('Y-m-d H:i:s', $beginOfDayString);
$beginOfDay = $beginOfDayObject->getTimestamp();
We can get the end of the day in an alternate manner using this longer version:
$endOfDayObject = clone $beginOfDayOject(); // Cloning because add() and sub() modify the object
$endOfDayObject->add(new DateInterval('P1D'))->sub(new DateInterval('PT1S'));
$endOfDay = $endOfDayOject->getTimestamp();
Timezone
The timezone can be set as well by adding a timestamp indicator to the format such as O and specifying the timestamp after creating the DateTime object:
$beginOfDay = DateTime::createFromFormat('Y-m-d H:i:s O', (new DateTime())->setTimezone(new DateTimeZone('America/Los_Angeles'))->setTimestamp($timestamp)->format('Y-m-d 00:00:00 O'))->getTimestamp();
Flexibility of DateTime
We can also get other information such as the beginning/end of the month or the beginning/end of the hour by changing the second format specified. For month: 'Y-m-01 00:00:00' and 'Y-m-t 23:59:59'. For hour: 'Y-m-d H:00:00' and 'Y-m-d H:59:59'
Using various formats in combination with add()/sub() and DateInterval objects, we can get the beginning or end of any period, although some care will need to be taken to handle leap years correctly.
Relevant Links
From the PHP docs:
DateTime
date with info on the format
DateTimeZone
DateInterval
You can use a combination of date() and mktime():
list($y,$m,$d) = explode('-', date('Y-m-d', $ts));
$start = mktime(0,0,0,$m,$d,$y);
$end = mktime(0,0,0,$m,$d+1,$y);
mktime() is smart enough to wrap months/years when given a day outside the specified month (jan 32nd will be feb 1st, etc)
You could convert the time to the current data and then use the strtotime function to find the start of the day and simply add 24 hours to that to find the end of the day.
You could also use the remainder operator (%) to find the nearest day. For example:
$start_of_day = time() - 86400 + (time() % 86400);
$end_of_day = $start_of_day + 86400;
The accepted answer unfortunately breaks due to a php bug that occurs in very specific scenarios. I'll discuss those scenarios, but first the answer using DateTime. The only difference between this and the accepted answer occurs after the // IMPORTANT line:
$dtNow = new DateTime();
// Set a non-default timezone if needed
$dtNow->setTimezone(new DateTimeZone('America/Havana'));
$dtNow->setTimestamp($timestamp);
$beginOfDay = clone $dtNow;
// Go to midnight. ->modify('midnight') does not do this for some reason
$beginOfDay->modify('today');
// now get the beginning of the next day
$endOfDay = clone $beginOfDay;
$endOfDay->modify('tomorrow');
// IMPORTANT
// get the timestamp
$ts = $endOfDay->getTimestamp();
// subtract one from that timestamp
$tsEndOfDay = $ts - 1;
// we now have the timestamp at the end of the day. we can now use that timestamp
// to set our end of day DateTime
$endOfDay->setTimestamp($tsEndOfDay);
So you'll note that instead of using ->modify('1 second ago'); we instead get the timestamp and subtract one. The accepted answer using modify should work, but breaks because of php bug in very specific scenarios. This bug occurs in timezones that change daylight savings at midnight, on the day of the year that clocks are moved "forward". Here is an example you can use to verify that bug.
bug example code
// a time zone, Cuba, that changes their clocks forward exactly at midnight. on
// the day before they make that change. there are other time zones which do this
$timezone = 'America/Santiago';
$dateString = "2020-09-05";
echo 'the start of the day:<br>';
$dtStartOfDay = clone $dtToday;
$dtStartOfDay->modify('today');
echo $dtStartOfDay->format('Y-m-d H:i:s');
echo ', '.$dtStartOfDay->getTimestamp();
echo '<br><br>the start of the *next* day:<br>';
$dtEndOfDay = clone $dtToday;
$dtEndOfDay->modify('tomorrow');
echo $dtEndOfDay->format('Y-m-d H:i:s');
echo ', '.$dtEndOfDay->getTimestamp();
echo '<br><br>the end of the day, this is incorrect. notice that with ->modify("-1 second") the second does not decrement the timestamp by 1:<br>';
$dtEndOfDayMinusOne = clone $dtEndOfDay;
$dtEndOfDayMinusOne->modify('1 second ago');
echo $dtEndOfDayMinusOne->format('Y-m-d H:i:s');
echo ', '.$dtEndOfDayMinusOne->getTimestamp();
echo '<br><br>the end of the day, this is correct:<br>';
$dtx = clone $dtEndOfDay;
$tsx = $dtx->getTimestamp() - 1;
$dty = clone $dtEndOfDay;
$dty->setTimestamp($tsx);
echo $dty->format('Y-m-d H:i:s');
echo ', '.$tsx;
bug example code output
the start of the day:
2020-03-26 00:00:00, 1585173600
the start of the *next* day:
2020-03-27 01:00:00, 1585260000
the end of the day, this is incorrect. notice that with ->modify("1 second ago") the
second does not decrement the timestamp by 1:
2020-03-27 01:59:59, 1585263599
the end of the day, this is correct:
2020-03-26 23:59:59, 1585259999
Today Starting date timestamp. Simple
$stamp = mktime(0, 0, 0);
echo date('m-d-Y H:i:s',$stamp);
$start_of_day = floor (time() / 86400) * 86400;
$end_of_day = ceil (time() / 86400) * 86400;
If your need both values in the same script. It is faster to +/- 86400 seconds to one of the variables than to fire both floor and ceil. For example:
$start_of_day = floor (time() / 86400) * 86400;
$end_of_day = $start_of_day + 86400;
For anyone that have this question in the future:
Any day code
<?php
$date = "2015-04-12 09:20:00";
$midnight = strtotime("midnight", strtotime($date));
$now = strtotime($date);
$diff = $now - $midnight;
echo $diff;
?>
Current day code
<?php
$midnight = strtotime("midnight");
$now = date('U');
$diff = $now - $midnight;
echo $diff;
?>
$date = (new \DateTime())->setTimestamp(1330581600);
echo $date->modify('today')->format('Y-m-d H:i:s'); // 2012-02-29 00:00:00
echo PHP_EOL;
echo $date->modify('tomorrow - 1 second')->format('Y-m-d H:i:s'); // 2012-02-29 23:59:59
$startOfDay = new \DateTime('tomorrow');
$startOfDay->modify('-1 day');
This works for me :)
A little late to the party, but here's another easy way to achieve what you're looking for:
$timestamp=1330581600;
$format = DATE_ATOM;
$date = (new DateTime())->setTimestamp($timestamp);
// Here's your initial date, created from the timestamp above
// 2012-03-01T06:00:00+00:00
$dateFromTimestamp = $date->format($format);
// This is the beginning of the day
// 2012-03-01T00:00:00+00:00
$startOfDay = $date->setTime(0,0);
// This is the beginning of the next day
// 2012-03-02T00:00:00+00:00
$startOfNextDay = $startOfDay->modify('+1 day');
I would personally avoid using the end of the day unless it's absolutely necessary. You can, of course, use 23:59:59 but this is not the actual end of the day (there's still 1 second left). What I do is use the start of the next day as my end boundary, for example:
$start = new DateTime('2021-11-09 00:00:00');
$end = new DateTime('2021-11-10 00:00:00');
if ($someDateTime >= $start && $someDateTime < $end) {
// do something
}
If I must use the end of the day, I'd go with calculating the start of the next day and then subtracting 1 microsecond from that.
$beginOfDay = (new DateTime('today', new DateTimeZone('Asia/Tehran')))->getTimestamp();
$endOfDay = $beginOfDay + 86399;
You can set a timezone by replacing "Asia/Tehran". One day is 86400 seconds, Don't ask me why 86399, It is a whisper in my mind that says it is 86399, So I do not even want to think about its truth.

Difference between dates

I want to calculate the difference between two times, one of which is the current time, and the other is just in the format HH:MM, always in the future.
If I just subtract $futuretime from $now, it should, of course, be a positive number.
This works fine until...
If $now is in the afternoon or evening and $futuretime is, say, 7AM next morning, how can I force it to understand the the time is always going to be in the future?
(It's for working out the time of something that occurs about every half an hour during working hours, and then stops until the following morning)
Thanks in advance!
Simply add a whole day to the difference if it is negative. Assuming that $now and $futuretime are timestamps (stored in seconds since midnight), simply do the following:
$diff = $futuretime - $now;
if ($diff < 0)
$diff += 24 * 3600;
If they are in HH:MM format:
list($future_hours, $future_mins) = explode(":", $futuretime);
$futuretime = $future_hours * 60 + $future_mins;
list($now_hours, $now_mins) = explode(":", $now);
$now = $now_hours * 60 + $now_mins;
$diff = $futuretime - $now;
if ($diff < 0)
$diff += 24 * 60;
Of course the latter case returns the difference in minutes, while the former returns the difference in seconds.
Edit: as Andy noted below in the comments, this is not a good solution if you care about changes in DST. See his solution for a better approach.
If you're on PHP 5.3+, use PHP's DateTime:
$d1 = new DateTime('14:52:10');
$d2 = new DateTime('12:12:10');
$diff = $d1->diff( $d2 );
var_dump( $diff );
You can simply convert both dates to timestamp, do the calculations and convert it to required format, i.e. days, hours and minutes. it's quite simple.

How to get duration in terms of minutes by subtracting a previous time stamp from the present time in PHP?

How to get duration in terms of minutes by subtracting a previous time stamp from the present time in PHP?
The format of time stamp is like
2009-12-05 10:35:28
I want to calculate how many minutes have passed.
How to do it?
To do this in MySQL use the TIMESTAMPDIFF function:
SELECT TIMESTAMPDIFF(MINUTE, date_lastaccess, NOW()) FROM session;
Where session is the table and date_lastaccess is a DATE / DATETIME field.
If you don't wanna add a library, you can do this pretty easily:
<?php
$date1 = "2009-12-05 10:35:28";
$date2 = "2009-12-07 11:58:12";
$diff = strtotime($date2) - strtotime($date1);
$minutes_passed = $diff/60;
echo $minutes_passed." minutes have passed between ".$date1." and ".$date2;
?>
Check out some pretty date libraries in PHP. Might have something for you. Here's one : http://www.zachleat.com/web/2008/02/10/php-pretty-date/
strtotime("now") - strtotime("2009-12-05 10:35:28")
That will get you seconds difference. Divide by 60 for minutes elapsed. If you have any information on the time zone of the initial timestamp, however, you'd need to adjust the "now" to a more comparable time
something like that
$second = strtotime('now') - strtotime($your_date);
$minute = $second / 60;
strtotime return the number of seconds since January 1 1970 00:00:00 UTC, so you can easily manipulate this. if you need don't want to have 35.5 minute you can use floor to round up the number. Last remark both time need to be in the same timezone or you are going to count the timezone difference also.
You could just use
$timestamp = time();
$diff = time() - $timestamp
$minutes = date( i, $diff );
function timeAgoMin($timestamp){
if(!is_int($timestamp)){
$timestamp = strtotime($timestamp);
}
return ((time() - $timestamp) / 60);
}

Categories