Andrew Morris
Andrew Morris

Reputation: 1652

How many seconds from midnight until specific Datetime

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:

Is there a nice short method of doing this?

Upvotes: 2

Views: 1978

Answers (2)

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;
?>

Upvotes: 2

gia
gia

Reputation: 757

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.

Upvotes: 1

Related Questions