PHP - strtotime() return 1970

3k views Asked by At

The following code snippet:

echo date("d.m.Y-H:i:s", strtotime("01.01.2000-11:12:32"));

returns me:

01.01.1970-01:00:00

What's the right way to convert "01.01.2000-11:12:32" to time/date object, for comparing it with the current timestamp?

e.g.

if (date("d.m.Y-H:i:s") > date("d.m.Y-H:i:s", strtotime("01.01.2000-11:12:32"))) {
    echo "future";
} else {
    echo "past";
}
3

There are 3 answers

0
Praveen Kumar Purushothaman On BEST ANSWER

This is due to localisation. Try giving a different format, as the format matters a lot:

echo date("d.m.Y-H:i:s", strtotime("01/01/2000 11:12:32"));
echo date("d.m.Y-H:i:s", strtotime("01-01-2000 11:12:32"));
  1. You should not have . for date and month separator.
  2. You cannot separate date and time using -.

If you are getting the input from another source, try using str_replace:

echo date("d.m.Y-H:i:s", strtotime(str_replace(array(".", "-"), array("/", " "), "01.01.2000-11:12:32")));

Output: http://ideone.com/d19ATK

0
Ionut Necula On

Try to replace . with -:

echo date("d.m.Y-H:i:s", strtotime(str_replace('.', '-', "01.01.2000 11:12:32")));

Also remove - between the date and time.

0
Mihai Matei On

You can use DateTime::createFromFormat

$date = DateTime::createFromFormat('d.m.Y-H:i:s', '01.01.2000-11:12:32');
$now = new DateTime();

if ($now > $date) {
    echo "future";
} else {
    echo "past";
}