2
select  DATE_FORMAT('8:48:30 AM', '%H:%i:%s')

It returns Null why ?

but when using

select  DATE_FORMAT(CURTIME(), '%H:%i:%s')

It return formatted value.

1
  • 1
    I believe that DATE_FORMAT expects its first parameter to be DATETIME type not only TIME. BTW I checked and on recent mysql it also gives null in the second form with warning: Incorrect datetime value: '11:35:22' Commented Jul 11, 2013 at 4:01

4 Answers 4

3

It's returning NULL because MySQL isn't successfully parsing the string into a valid DATETIME value.

To fix the problem, use the STR_TO_DATE function to parse the string into a TIME value,

SELECT STR_TO_DATE('8:48:30 AM', '%h:%i:%s %p') 

Then, to get the TIME value converted to a string in a particular format, use the TIME_FORMAT function, e.g. 24-hour clock representation:

SELECT TIME_FORMAT(STR_TO_DATE( '8:48:30 AM', '%h:%i:%s %p'),'%H:%i:%s')

returns:

--------
08:48:30
Sign up to request clarification or add additional context in comments.

1 Comment

there is not function named STR_TO_TIME in mysql
2

The method DATE_FORMAT is used to display date and time, however in the first you are not assigning any date except time, so its is throwing null.

From the manuals -

DATE_FORMAT Formats the date value according to the format string.

In MySql version 5.5 SELECT DATE_FORMAT( CURTIME( ) , '%H:%i:%s' ) returns null

Comments

2

DATE_FORMAT 's first parameter is of type DATETIME. On recent mysql server versions both your queries return NULL.

So the answer to your question is that this difference in behaviour is because of a bug in your mysql version - in some way it converts the TIME to DATETIME, while it cannot convert the string to DATETIME.

Here is also an example of a working query:

select  DATE_FORMAT(NOW(), '%H:%i:%s')

NOW() returns a DATETIME while CURTIME() returns TIME.

Comments

0

To my knowledge, I think it's because MySQL recognises the function as a time, and therefore knows how to handle it. Whereas, in the first example, it regards it as a string and doesn't know what to do with it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.