如何从SQL Server中检索YYYY-MM-DD格式的日期?我需要这个工作与SQL Server 2000及更高。是否有一个简单的方法来执行这在SQL Server或它会更容易转换后,我检索的结果集?

我已经阅读了微软Technet上的CAST和CONVERT,但我想要的格式没有列出,改变日期格式也不是一个选项。


当前回答

以防有人想用另一种方式来做,发现了这个。

select convert(datetime, '12.09.2014', 104)

这将德国日期格式的字符串转换为datetime对象。

为什么是104年?请看这里:http://msdn.microsoft.com/en-us/library/ms187928.aspx

其他回答

对于那些也想要时间部分的人(我想),下面的片段可能会有所帮助

SELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) -- yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm
                              --example -- 2008-10-02T10:52:47.513

将GetDate()更改为字符串格式:

SELECT FORMAT(GetDate(), 'yyyy-MM-dd HH:mm:ss')
SELECT Code,Description FROM TABLE

-- This will Include only date part of 14th March 2010. Any date with date companents will not be considered.
WHERE ID= 1 AND FromDate >= CONVERT(DATETIME, '2010-02-14', 126) AND ToDate <= DATEADD(dd, 1, CONVERT(DATETIME, '2010-03-14', 126))

-- This will Include the whole day of 14th March 2010
--WHERE ID= 1 AND FromDate >= CONVERT(DATETIME, '2010-02-14', 126) AND ToDate < DATEADD(dd, 1, CONVERT(DATETIME, '2010-03-14', 126))

您所需要的表格在图书在线文档中列出。

http://msdn.microsoft.com/en-us/library/aa226054 (SQL.80) . aspx

例如,尝试以下方法:

select convert(varchar,getDate(),120)
select convert(varchar(10),getDate(),120)
 IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);

cmdGetPaymentStatement.Parameters.AddWithValue("@pStartDate", DateTime.Parse("22/12/2017", culture, System.Globalization.DateTimeStyles.AssumeLocal)).IsNullable = true;