PHP : strtotime() returns always 01/01/1970
Asked Answered
S

3

5

I am trying to display dates in the European format (dd/mm/yyyy) with strtotime but it always returns 01/01/1970.

Here is my codeline :

echo "<p><h6>".date('d/m/Y', strtotime($row['DMT_DATE_DOCUMENT']))."</h6></p>";

In my database, the field is a varchar and records are formated like yyyy.mm.dd

I use the same codeline for another field that is formated like yyyy-mm-dd (varchar too) and it works fine.

Thanks for your help.

Stepp answered 8/6, 2012 at 9:41 Comment(1)
That's probably because strtotime assumes mm/dd/yyyy instead and if you input a date like 13/2/2012 it complain that there is no 13th month and give you time 0 (1/1/1970)Sclerometer
L
4

Since the format yyyy-mm-dd works, try to replace . with -:

date('d/m/Y', strtotime(str_replace('.', '-', $row['DMT_DATE_DOCUMENT'])));
Lagunas answered 8/6, 2012 at 9:44 Comment(0)
B
4

Quoting from the strtotime page in the PHP manual.

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

So in your case it should either be in format YYYY-MM-DD or d.m.y.

If you want to parse your custom format then use date_create_from_format

For example,

date_create_from_format('Y.m.d',$row['DMT_DATE_DOCUMENT'])
Boehmenist answered 8/6, 2012 at 9:54 Comment(0)
P
3

Try with:

$date = date_parse_from_format("Y.m.d", $row['DMT_DATE_DOCUMENT']);
$time = mktime($date['hour'], $date['minute'], $date['second'], $date['month'], $date['day'], $date['year']);
echo "<p><h6>".date('d/m/Y', $time)."</h6></p>";

(Using date_parse_from_format() instead of strtotime())

Or just:

$date = date_parse_from_format("Y.m.d", $row['DMT_DATE_DOCUMENT']);
echo "<p><h6>{$date['day']}/{$date['month']}/{$date['year']}</h6></p>";
Pibroch answered 8/6, 2012 at 9:45 Comment(1)
Yes, only that date won't accept the direct output of date_parse_from_format.Mindexpanding

© 2022 - 2024 — McMap. All rights reserved.