Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strtotime of today

Tags:

php

Hallo, I want to find the difference between today and another date,

convert todays date into unix time format here

 <?php
    echo '1st one'.strtotime(date("d.m.Y")).'<br>';
    echo '2nd one'.strtotime(date("m.d.Y")).'<br>';
    ?>

The first echo is producing some value, but not the second one. What is the bug in it...please help..

like image 513
satya Avatar asked Dec 22 '22 22:12

satya


2 Answers

strtotime makes assumptions based on the date format you give it. For instance

date("Y-m-d", strtotime(date("d.m.Y"))) //=> "2010-09-27"
date("Y-m-d", strtotime(date("m.d.Y"))) //=> "1969-12-31"

Note that when given an invalid date, strtotime defaults to the timestamp for 1969-12-31 19:00:00, so when you end up with an unexpected date in 1969, you know you're working with an invalid date.

Because strtotime is looking for day.month.year when you use . as the delimiter, so it sees "9.27.2010" as the 9th day of the 27th month, which obviously doesn't exist.

However, if you change it to use / as the delimiter:

date("Y-m-d", strtotime(date("d/m/Y"))) //=> "1969-12-31"
date("Y-m-d", strtotime(date("m/d/Y"))) //=> "2010-09-27"

In this case, strtotime expects dates in month/day/year format.

If you want to be safe, Y-m-d is generally a good format to use.

like image 134
Daniel Vandersluis Avatar answered Dec 24 '22 13:12

Daniel Vandersluis


It's worth pointing out that strtotime() does accept words like "today" as valid input, so you don't need to put a call to date() in there if all you want is today's date. You could just use strtotime('today');.

Come to think of it, a simple call to time(); will get you the current time stamp too.

But to actually answer the question, you need to consider that d.m.Y and m.d.Y are ambiguous - if the day of the month is less than the 12th, it is impossible to tell which of those two date formats was intended. Therefore PHP only accepts one of them (I believe it uses m/d/Y if you have slashes, but for dots or dashes it assumes d-m-Y.

If you're using strtotime() internally for converting date formats, etc, there is almost certainly a better way to do it. But if you really need to do this, then use 'Y-m-d' format, because it's much more universally reliable.

On the other hand, if you're accepting date input from your users and assuming that strtotime() will deal with anything thrown at it, then sadly you're wrong; strtotime() has some quite big limitations, of which you've found one. But there are a number of others. If you plan to use strtotime() for this sort of thing then you need to do additional processing as well. There may also be better options such as using a front-end Javascript date control to make it easier for your users without having to rely on strtotime() to work out what they meant.

like image 35
Spudley Avatar answered Dec 24 '22 11:12

Spudley