string 如何在 SQL Server 中将“dd/mm/yyyy”字符串转换为日期时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2780668/
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
How to convert a "dd/mm/yyyy" string to datetime in SQL Server?
提问by Sim
I tried this
我试过这个
SELECT convert(datetime, '23/07/2009', 111)
SELECT convert(datetime, '23/07/2009', 111)
but got this error
但得到这个错误
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
However
然而
SELECT convert(datetime, '07/23/2009', 111)
SELECT convert(datetime, '07/23/2009', 111)
is OK though
不过没关系
How to fix the 1st one ?
如何修复第一个?
回答by Grzegorz Oledzki
The last argument of CONVERT
seems to determine the format used for parsing. Consult MSDN docs for CONVERT.
的最后一个参数CONVERT
似乎决定了用于解析的格式。有关CONVERT 的信息,请参阅 MSDN 文档。
111
- the one you are using is Japan yy/mm/dd
.
111
- 您使用的是日本yy/mm/dd
。
I guess the one you are looking for is 103
, that is dd/mm/yyyy
.
我猜你要找的103
就是dd/mm/yyyy
。
So you should try:
所以你应该尝试:
SELECT convert(datetime, '23/07/2009', 103)
回答by Alex
Try:
尝试:
SELECT convert(datetime, '23/07/2009', 103)
this is British/French standard.
这是英国/法国标准。
回答by RNT665
SELECT convert(varchar(10), '23/07/2009', 111)
回答by Qwerty-uiop
SQL Server by default uses the mdy
date format and so the below works:
SQL Server 默认使用mdy
日期格式,因此以下工作:
SELECT convert(datetime, '07/23/2009', 111)
and this does not work:
这不起作用:
SELECT convert(datetime, '23/07/2009', 111)
I myself have been struggling to come up with a single query that can handle both date formats: mdy
and dmy
.
我自己一直在努力想出一个可以处理两种日期格式的查询:mdy
和dmy
.
However, you should be ok with the third date format - ymd
.
但是,您应该可以使用第三种日期格式 - ymd
.
回答by user6434845
SELECT convert(datetime, '23/07/2009', 103)
回答by nayan
You can convert a string to a date easily by:
您可以通过以下方式轻松地将字符串转换为日期:
CAST(YourDate AS DATE)