简体   繁体   English

将varchar格式化为日期时间SQL Server 2008

[英]format varchar to datetime SQL Server 2008

I have a table in which one of the columns is varchar but stores datetime. 我有一个表,其中的一列是varchar但存储了datetime。

Instead of saving date as varchar I am creating a new column. 我没有将日期另存为varchar,而是创建了一个新列。 To copy existing date I use 要复制我使用的现有日期

SELECT CONVERT(Datetime,entryTime,101)

The original date is '7/13/2015 2:40:44 AM' 原始日期是'7/13/2015 2:40:44 AM''7/13/2015 2:40:44 AM'

After using convert function I get 使用转换功能后,我得到

'2015-07-13 02:40:44.000'

What should I use to format it, to look like the original? 我应该用什么来格式化它,使其看起来像原始的?

instead of using cast, use convert like you tried but if the date format is wrong then try using a different region. 与其使用强制转换,不如尝试使用convert,但是如果日期格式错误,请尝试使用其他区域。

I use this excellent post on date/times, have a read and it should help. 我在日期/时间上使用了出色的帖子,请阅读并对其有所帮助。

Try this, 尝试这个,

DECLARE @Date AS DATETIME='7/13/2015 2:40:44 AM' --Original Date
DECLARE @UpdateDate AS DATETIME=''
SELECT @UpdateDate = CONVERT(DATETIME ,@Date ,101)  --Converted Date
--SELECT @UpdateDate 
SELECT CONVERT(VARCHAR(10) ,@UpdateDate ,101) +' '+CONVERT(VARCHAR(8) ,@UpdateDate ,108) ExpectedDate --As per your expected result.

With AM/PM try below, 使用AM / PM,请尝试以下操作,

SELECT CONVERT(VARCHAR(10) ,@UpdateDate ,101)+' '+CONVERT(VARCHAR(8) ,@UpdateDate ,108) 
      +' '+RIGHT(CONVERT(VARCHAR(30) ,@UpdateDate ,9) ,2) ExpectedDate --As per your expected result with AM/PM

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

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