Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format timestamp from MYSQL query

Tags:

date

sql

mysql

I have a mysql query that has a column CreationDate in the format of "timestamp". Example:

2013-03-27 18:32:45

I would like for the sql query to format it in this fashion (12hr format with seconds):

Friday 3/28/2013 12:52:34 PM

I would like to handle this at the sql level rather than php or .js, etc.

Query:

SELECT a.ID, a.CreationDate, a.Content, a.Type, u.Nickname
FROM Announcements a 
INNER JOIN Accounts u ON a.FromAccountID = u.AccountID
WHERE a.Status  = '1' AND u.Status = '1'
ORDER BY a.ID DESC
like image 221
user1157800 Avatar asked Mar 28 '13 19:03

user1157800


People also ask

What is the format of TIMESTAMP in MySQL?

MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

How do I change the format of a TIMESTAMP in SQL?

select to_char(sysdate, 'YYYY-MM-DD') from dual; To get this format by default, set it in your session's NLS_DATE_FORMAT parameter: alter session set NLS_DATE_FORMAT = 'YYYY-MM-DD'; You can also set the NLS_TIMESTAMP_FORMAT and NLS_TIMESTAMP_TZ_FORMAT .

How do I write a TIMESTAMP in SQL query?

The basic syntax of “timestamp” data type in SQL is as follows : Timestamp 'date_expression time_expression'; A valid timestamp data expression consists of a date and a time, followed by an optional BC or AD.

How do you format a TIMESTAMP?

Timestamp data must be in the form YYYY-MM-DD-hh-mm, optionally followed by 1 to 12 fractional seconds. The default size of a timestamp is 26, with 6 fractional seconds. For a free-form timestamp definition, you use the parameter of the TIMESTAMP keyword to control the number of fractional seconds.


2 Answers

You will want to use DATE_FORMAT:

SELECT a.ID, 
  date_format(a.CreationDate, '%W %m/%d/%Y %l:%i %p') CreationDate, 
  a.Content, 
  a.Type, 
  u.Nickname 
FROM Announcements a 
INNER JOIN Accounts u 
  ON a.FromAccountID = u.AccountID 
WHERE a.Status = '1' 
  AND u.Status = '1' 
ORDER BY a.ID DESC

The MySQL docs will show what specifiers you will use to get the format that you want (See SQL Demo).

If you want to keep seconds, then you will use:

date_format(a.CreationDate, '%W %m/%d/%Y %r')
like image 62
Taryn Avatar answered Oct 02 '22 21:10

Taryn


DATE_FORMAT(a.CreationDate,'%W %c/%e/%Y %h:%i %p')

like image 45
brbcoding Avatar answered Oct 02 '22 20:10

brbcoding