3

I have a date which is say like this

$given_date = '2014-12-25'; //Y-m-d format

Now i want to get the midnight timestamp of the given date, so I am doing this method

$midnight = strtotime(date('Y-m-d',$given_date).' 00:00:00');

Am I doing it right??

or I can use something like this?

$midnight = strtotime("midnight $given_date");

Which is better?

segarci
  • 739
  • 1
  • 11
  • 19
Saswat
  • 12,320
  • 16
  • 77
  • 156
  • possible duplicate of [how to convert date and time to timestamp in php?](http://stackoverflow.com/questions/17585632/how-to-convert-date-and-time-to-timestamp-in-php) – Aleksandar Vasić Dec 31 '14 at 08:05
  • 2
    stop refering my answer as a duplicate one... its not... i wanted to know which one is better.... – Saswat Dec 31 '14 at 08:06

3 Answers3

18

I would prefer a more OO approach instead of fiddling around with strings:

$date = new DateTime($given_date);
$date->setTime(0,0,0);

// echo $date->format('Y-m-d H:i:s');
echo $date->getTimestamp();
Axel Amthor
  • 10,980
  • 1
  • 25
  • 44
  • `echo $date->getTimestamp();` OP wants the timestamp. But I still doesn't get the "is better". Faster ? Readable ? – Debflav Dec 31 '14 at 08:27
  • 1
    @Debflav the "is better" in this approach is, that dates are handled as `DateTime` objects and not as strings and that the `DateTime` class gives more control on the calculation of dates and times. For me it's still unclear, which "midnight" is actually wanted, the next from now on or the past from a given date, which actually belongs to the day before. Running in to this, and probably some time zone issues as well and you end up in a mess with strings. – Axel Amthor Dec 31 '14 at 12:39
  • The "is better" was more for the OP. I'm agree with you and the use of DateTime object, maybe your explanation can be in your answer. – Debflav Dec 31 '14 at 13:05
6

Using the static method createFromFormat from DateTime you can force the time-parts to be reset to 0 using '|':

$date = DateTime::createFromFormat('Y-m-d|', $given_date);
echo $date->format('Y-m-d H:i:s');
Blablaenzo
  • 1,027
  • 1
  • 11
  • 14
1

It is also possible to do it with:

list($y, $m, $d) = explode('-', $given_date);
$midnight = mktime(0, 0, 0, $m, $d, $y);
hsz
  • 148,279
  • 62
  • 259
  • 315