MySQL 将日期时间值转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2392413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert datetime value into string
提问by Khilen
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 中使用 NOW() 获取当前日期和时间。我想将日期值转换为 varchar 并将其与另一个字符串连接。我该怎么做?
回答by Frank Heikens
回答by Chords
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:
这是超旧的,但我想我会添加我的 2c。DATE_FORMAT
确实返回一个字符串,但我正在寻找该CAST
函数,在我已经在数据库中有一个日期时间字符串并且需要对其进行模式匹配的情况下:
http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html
http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html
In this case, you'd use:
在这种情况下,您将使用:
CAST(date_value AS char)
CAST(date_value AS char)
This answers a slightly different question, but the question title seems ambiguous enough that this might help someone searching.
这回答了一个稍微不同的问题,但问题标题似乎不够明确,这可能有助于某人进行搜索。
回答by PROJECT D - DSS
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
.
基于完整日期的日期字段上的 10 个字符
yyyy-MM-dd
。基于全职时间字段的 8 个字符
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.
因为如果您阅读它,实际上日期和时间字段就像字符串一样。但是当然你会在更新或插入它时出错。