Convert datetime value into string

MysqlDatabaseStringDatetime

Mysql Problem Overview


I am fetching the current date & time using NOW() in mysql. I want to convert the date value into a varchar and concat it with another string. How do I do it?

Mysql Solutions


Solution 1 - Mysql

Use DATE_FORMAT()

SELECT
  DATE_FORMAT(NOW(), '%d %m %Y') AS your_date;

Solution 2 - Mysql

This is super old, but I figured I'd add my 2c. DATE_FORMAT does indeed return a string, but I was looking for the CAST function, in the situation that I already had a datetime string in the database and needed to pattern match against it:

http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html

In this case, you'd use:

CAST(date_value AS char)

This answers a slightly different question, but the question title seems ambiguous enough that this might help someone searching.

Solution 3 - Mysql

Try this:

concat(left(datefield,10),left(timefield,8))
  • 10 char on date field based on full date yyyy-MM-dd.

  • 8 char on time field based on full time hh:mm:ss.

It depends on the format you want it. normally you can use script above and you can concat another field or string as you want it.

Because actually date and time field tread as string if you read it. But of course you will got error while update or insert it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKhilenView Question on Stackoverflow
Solution 1 - MysqlFrank HeikensView Answer on Stackoverflow
Solution 2 - MysqlChordsView Answer on Stackoverflow
Solution 3 - MysqlPROJECT D - DSSView Answer on Stackoverflow