Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting an SQL timestamp with PHP

Tags:

I have a mySQL database with a timestamp field. It currently only has one entry while I'm testing, it is

2010-02-20 13:14:09 

I am pulling from the database and using

echo date("m-d-Y",$r['newsDate']) 

My end result is showing as

12-31-69 

Anyone know why?

Edit: editedit: disregard that edit... the FTP addon for notepad++ timed out and unfortunately doesn't display an error when it can't synch.

like image 843
Chris Sobolewski Avatar asked Feb 20 '10 21:02

Chris Sobolewski


People also ask

How do I format a timestamp in SQL?

The CURRENT_TIMESTAMP function returns the current date and time, in a 'YYYY-MM-DD hh:mm:ss. mmm' format. Tip: Also look at the GETDATE() function.

What is timestamp format in PHP?

Summary. The date function in PHP is used to format the timestamp into a human desired format. The timestamp is the number of seconds between the current time and 1st January, 1970 00:00:00 GMT. It is also known as the UNIX timestamp. All PHP date() functions use the default time zone set in the php.ini file.

How can I timestamp in PHP?

Definition and Usage. The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.


2 Answers

The date function expects an UNIX timestamp as its second parameter -- which means you have to convert the date you get from the DB to an UNIX timestamp, which can be done using strtotime :

$db = '2010-02-20 13:14:09'; $timestamp = strtotime($db); echo date("m-d-Y", $timestamp); 

And you'll get :

02-20-2010 


You were passing the '2010-02-20 13:14:09' string to the date function ; that string is not a valid UNIX Timestamp.

'12-31-69' is probably 1970-01-01, in your locale ; and 1970-01-01 is the Epoch -- the date that corresponds to the 0 UNIX Timestamp.

like image 62
Pascal MARTIN Avatar answered Nov 24 '22 09:11

Pascal MARTIN


For starters, the php date() function is expecting seconds as the second variable. So that accounts for why your date is displaying wrong. Check this source on that issue.

Which then provides us the answer to the problem, to get PHP to format the date from a SQL timestamp correctly, we just change the query a tad...

SELECT author, `when` 

Change it to...

SELECT author, UNIX_TIMESTAMP(`when`) 

Then use the PHP date function, with the variable that is storing the result of that above SQL query.

like image 20
Urda Avatar answered Nov 24 '22 08:11

Urda