DEV Community

Nir Gofman
Nir Gofman

Posted on

That's how I came back in time

Few days ago one of my clients asked for a little php script that will add the date when users opens a new ticket in his website's tickets system where they can contact the website administrators..

It's pretty simple right?, all it requires is to add a new column in the 'Tickets' MySQL table (I love to define this column as tinytext and not as date field).
And, in the $_POST form operation - get the date with the php date() function, add or reduce hours or minutes depends on the server time.

Surprisingly, in the DB I saw the date 1/1/1970 1:00 for every form entry. What The H....
So I started exploring.
This is how I get the date:

$newdate = date("d/m/Y H:i");
$newdate = strtotime('+1 hour', strtotime ($newdate));
$newdate = date ( 'd/m/Y H:i' , $newdate );
echo $newdate;

it outputs 1/1/1970 2:00, if I delete the second and the third lines (which adds an hour) the output is the actual date and time. WHY?

Steps for debugging this issue:

1. Enabling error display and error reporting in the php file:

ini_set('display_errors', 1);
error_reporting(E_ALL);

One's we enabled that we can't see ANY errors. Seems like everything is O.K.

2. Exploring the strtotime() function in the menual:

Description:
strtotime ( string $time [, int $now = time() ] ) : int
"The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied."

I was given 'now' when I wanted to add 1 hour. Which means the format I'm trying to pass is not valid.
After more research I needed to replace the Slashes ( / ) with Hyphen ( - ) And the edit looks like this:

$newdate = date("d-m-Y H:i");
$newdate = strtotime ( '+1 hour' , strtotime ( $newdate ) ) ;
$newdate = date ( 'd/m/Y H:i' , $newdate );
echo $newdate;

That's it!
These slashes made the date to be in invalid format which strtotime() function can't handle.

Conclusion

Next time, I will read the formats valid for all the php functions, I didn't expected that this / so different from this - .

Thank you for reading,
Nir.

Top comments (0)