简体   繁体   English

将datetime转换为特定格式?

[英]Convert datetime to specific format?

I want to convert a datetime to a specific format. 我想将日期时间转换为特定格式。 The conversion should result in a variable of type datetime and not char or varchar. 该转换将导致日期时间类型的变量,而不是char或varchar。 How do I do this in SQL server 2000, 2005 and 2008 ? 如何在SQL Server 2000、2005和2008中执行此操作?

select CONVERT(varchar(30),getdate(),120)

I tried this, but it gives me a string. 我试过了,但这给了我一个字符串。 I want a datetime without the milli-seconds. 我想要一个没有毫秒的日期时间。 SS 2012 has an option for this, but not previous versions. SS 2012为此提供了一个选项,但以前的版本没有。

http://blog.sqlauthority.com/2012/11/21/sql-server-display-datetime-in-specific-format-sql-in-sixty-seconds-033-video/ http://blog.sqlauthority.com/2012/11/21/sql-server-display-datetime-in-specific-format-sql-in-sixty-seconds-033-video/

You can't have it both ways ... a variable of type "datetime" is defined as: 您不能同时使用这两种方式...类型为“ datetime”的变量定义为:

Defines a date that is combined with a time of day 
with fractional seconds that is based on a 24-hour clock

You can CONVERT and DISPLAY in whatever format you choose, but the datetime data type will always have the milliseconds, even if you set them to zero. 您可以选择任何格式转换和显示,但是即使将日期时间数据类型设置为零,日期时间数据类型也始终具有毫秒数。

You can remove the milliseconds from the datetime like this: 您可以像这样从日期时间中删除毫秒:

DATEADD(ms, -DATEPART(ms, date), date) > '2013-11-18 03:21:52'

Also check SQL Server Date Formats 还要检查SQL Server日期格式

or may be try like this to remove the millisecond part:- 或者可以这样尝试删除毫秒部分:-

declare @str datetime
set @str = '2013-11-18 17:24:05.784'
select convert(datetime, convert(char(19), @str, 126))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM