user3636636
user3636636

Reputation: 2499

PHP strtotime only converting correctly when adding days

I am using strtotime in PHP, and getting two different result from the same input. I cannot work out why.

$startDate = 1468467219;
$oldDate = date('d/m/Y', strtotime($startDate));
$newDate = date('d/m/Y', strtotime('+3 weekdays', $startDate));

The original date is 14/07/2016 01.33 PM

$newDate is returning 19/07/2016 As expected.

$oldDate is returning 01/01/1970 Not the expected result - should be 14/07/2016.

I have tried other functions inside strtotime and they all produce the correct result. What am I missing? Why can I not simply just pass 1468467219 to strtotime without modifying it?

Upvotes: 0

Views: 460

Answers (2)

Marko Krstic
Marko Krstic

Reputation: 1447

you should only use:

$oldDate = date('d/m/Y', $startDate);

so, without strtotime($startDate)

When you are using strtotime, second parameter should be timestamp, but in your case it was the first one. But as first param should be one of Date and Time Formats.

Here more: http://php.net/manual/en/function.strtotime.php

Upvotes: 1

BeetleJuice
BeetleJuice

Reputation: 40916

You are misusing strtotime. This function takes a string representation of a date, and returns a timestamp. Instead you're feeding it a timestamp

$startDate = 1468467219;
$oldDate = date('d/m/Y', strtotime($startDate));

Since no common date format is expressed as "today is 1468467219", the function is unable to parse it and returns false.

var_dump(strtotime($startDate)) //<-- boolean FALSE

When you go on to feed FALSE to the date function, it can't parse it either, so it returns the wrong date: 01/01/1970.

To get the result you need just feed the timestamp directly to date:

$oldDate = date('d/m/Y', $startDate);

Upvotes: 0

Related Questions