Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php strtotime not working

so I converted this string to timestamp using strtotime:

strtotime("1 Nov, 2001");

which results into the timestamp 1320177660

but then when I tried converted 1320177660 into a normal date format again using an online timestamp converter, the year ended up being 2011 rather than 2001...

what am I doing wrong?

like image 234
kamikaze_pilot Avatar asked Jan 20 '23 23:01

kamikaze_pilot


2 Answers

As @Evan Mulawski's comment says, the "2001" is being interpreted as the time, not the year. Take out the comma to get PHP to interpret the "2001" as a year:

<?php
$ts = strtotime("1 Nov 2001");
echo $ts . "\n";
$st = strftime("%B %d, %Y, %H:%M:%S", $ts);
echo $st . "\n";
?>

Output:

1004590800
November 01, 2001, 00:00:00

like image 144
GreenMatt Avatar answered Jan 28 '23 03:01

GreenMatt


You're not doing anything wrong - it's just that strtotime isn't infallible.

As such, if you know the string is always going to be in a certain format, it's sometimes advisable to parse the date yourself, or if you're running PHP 5.3.x, you could use DateTime::createFromFormat to parse the string for you.

like image 26
John Parker Avatar answered Jan 28 '23 02:01

John Parker