← back to code snippets


PHP timestamping and fwrite

Posted on January 6th, 2014 in PHP

Say you’ve got a date, 12/25/2014, and you want to store the timestamp in your database.

just do this:

$mydate=‘12/25/2014’

$timestamp = DateTime::createFromFormat(’m/d/Y’, $mydate)->getTimestamp();  

Notice above that createFromFormat(’m/d/Y’) matches the format of $mydate m/d/y….so if $mydate was 2014.12.25, we’d be rolling with createFromFormat('Y.m.d’)


I used this in an automated process where $mydate was always different, and sometimes there was no date coming through, so the function failed.

To find out what was going on, I used some PHP functions that allow you to write to a file:

//as above:

$mydate='12/25/2014’

$timestamp = DateTime::createFromFormat(’m/d/Y’, $mydate)->getTimestamp();  

//next section added to write to file:

$File = “/var/www/mysite/date.txt”; 

$Handle = fopen($File, 'w’);
$Data = $mydate;
fwrite($Handle, $Data.“|”.$timestamp);
fclose($Handle);

In fwrite, I’ve written the original date, and the timestamp to the file.