Sql Server字符串到日期轉換

[英]Sql Server string to date conversion


I want to convert a string like this:

我想要像這樣轉換一個字符串:

'10/15/2008 10:06:32 PM'

into the equivalent DATETIME value in Sql Server.

在Sql Server中轉換為等效的DATETIME值。

In Oracle, I would say this:

在甲骨文,我想說:

TO_DATE('10/15/2008 10:06:32 PM','MM/DD/YYYY HH:MI:SS AM')

This question implies that I must parse the string into one of the standard formats, and then convert using one of those codes. That seems ludicrous for such a mundane operation. Is there an easier way?

這個問題意味着我必須將字符串解析為一個標准格式,然后使用其中的一個代碼進行轉換。對於這樣一個平凡的手術來說,這似乎是荒唐可笑的。有更簡單的方法嗎?

10 个解决方案

#1


28  

SQL Server (2005, 2000, 7.0) does not have any flexible, or even non-flexible, way of taking an arbitrarily structured datetime in string format and converting it to the datetime data type.

SQL Server(2005、2000、7.0)沒有任何靈活的、甚至是不靈活的方法來采用字符串格式的任意結構化datetime並將其轉換為datetime數據類型。

By "arbitrarily", I mean "a form that the person who wrote it, though perhaps not you or I or someone on the other side of the planet, would consider to be intuitive and completely obvious." Frankly, I'm not sure there is any such algorithm.

我說的“武斷”,是指“寫這篇文章的人,盡管可能不是你、我或地球另一邊的人,會認為這是一種直覺的、完全顯而易見的形式。”坦白地說,我不確定是否存在這樣的算法。

#2


214  

Try this

試試這個

Cast('7/7/2011' as datetime)

and

Convert(varchar(30),'7/7/2011',102)

See CAST and CONVERT (Transact-SQL) for more details.

有關更多細節,請參見CAST和CONVERT (Transact-SQL)。

#3


36  

Run this through your query processor. It formats dates and/or times like so and one of these should give you what you're looking for. It wont be hard to adapt:

通過查詢處理器運行此操作。它格式化日期和/或類似的時間,其中之一應該給你你想要的。這並不難適應:

Declare @d datetime
select @d = getdate()

select @d as OriginalDate,
convert(varchar,@d,100) as ConvertedDate,
100 as FormatValue,
'mon dd yyyy hh:miAM (or PM)' as OutputFormat
union all
select @d,convert(varchar,@d,101),101,'mm/dd/yy'
union all
select @d,convert(varchar,@d,102),102,'yy.mm.dd'
union all
select @d,convert(varchar,@d,103),103,'dd/mm/yy'
union all
select @d,convert(varchar,@d,104),104,'dd.mm.yy'
union all
select @d,convert(varchar,@d,105),105,'dd-mm-yy'
union all
select @d,convert(varchar,@d,106),106,'dd mon yy'
union all
select @d,convert(varchar,@d,107),107,'Mon dd, yy'
union all
select @d,convert(varchar,@d,108),108,'hh:mm:ss'
union all
select @d,convert(varchar,@d,109),109,'mon dd yyyy hh:mi:ss:mmmAM (or PM)'
union all
select @d,convert(varchar,@d,110),110,'mm-dd-yy'
union all
select @d,convert(varchar,@d,111),111,'yy/mm/dd'
union all
select @d,convert(varchar,@d,12),12,'yymmdd'
union all
select @d,convert(varchar,@d,112),112,'yyyymmdd'
union all
select @d,convert(varchar,@d,113),113,'dd mon yyyy hh:mm:ss:mmm(24h)'
union all
select @d,convert(varchar,@d,114),114,'hh:mi:ss:mmm(24h)'
union all
select @d,convert(varchar,@d,120),120,'yyyy-mm-dd hh:mi:ss(24h)'
union all
select @d,convert(varchar,@d,121),121,'yyyy-mm-dd hh:mi:ss.mmm(24h)'
union all
select @d,convert(varchar,@d,126),126,'yyyy-mm-dd Thh:mm:ss:mmm(no spaces)'

#4


31  

In SQL Server Denali, you will be able to do something that approaches what you're looking for. But you still can't just pass any arbitrarily defined wacky date string and expect SQL Server to accommodate. Here is one example using something you posted in your own answer. The FORMAT() function and can also accept locales as an optional argument - it is based on .Net's format, so most if not all of the token formats you'd expect to see will be there.

在SQL Server Denali中,您將能夠做一些接近您所查找的內容的事情。但是,您仍然不能僅僅傳遞任何任意定義的、古怪的日期字符串,並期望SQL Server能夠適應。這里有一個例子,你在自己的答案里貼了一些東西。FORMAT()函數,並且還可以接受locale作為可選參數——它基於。net的格式,所以您期望看到的大多數(如果不是所有的話)令牌格式都在那里。

DECLARE @d DATETIME = '2008-10-13 18:45:19';

-- returns Oct-13/2008 18:45:19:
SELECT FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss');

-- returns NULL if the conversion fails:
SELECT TRY_PARSE(FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);

-- returns an error if the conversion fails:
SELECT PARSE(FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);

I strongly encourage you to take more control and sanitize your date inputs. The days of letting people type dates using whatever format they want into a freetext form field should be way behind us by now. If someone enters 8/9/2011 is that August 9th or September 8th? If you make them pick a date on a calendar control, then the app can control the format. No matter how much you try to predict your users' behavior, they'll always figure out a dumber way to enter a date that you didn't plan for.

我強烈建議你采取更多的控制和清潔你的數據輸入。讓人們在freetext表單字段中使用任何格式輸入日期的日子應該已經一去不復返了。如果有人是在2011年8月9日或9月8日入住的話?如果你讓他們在日歷控件上選擇日期,那么應用程序就可以控制格式。無論你多么努力地去預測用戶的行為,他們總是會想出一個愚蠢的方式來輸入你沒有計划的約會。

Until Denali, though, I think that @Ovidiu has the best advice so far... this can be made fairly trivial by implementing your own CLR function. Then you can write a case/switch for as many wacky non-standard formats as you want.

不過,在德納里之前,我認為@Ovidiu提供了迄今為止最好的建議……通過實現您自己的CLR函數,這可以變得非常簡單。然后,您可以編寫一個case/switch,用於您想要的任何古怪的非標准格式。


UPDATE for @dhergert:

@dhergert更新:

SELECT TRY_PARSE('10/15/2008 10:06:32 PM' AS DATETIME USING 'en-us');
SELECT TRY_PARSE('15/10/2008 10:06:32 PM' AS DATETIME USING 'en-gb');

Results:

結果:

2008-10-15 22:06:32.000
2008-10-15 22:06:32.000

You still need to have that other crucial piece of information first. You can't use native T-SQL to determine whether 6/9/2012 is June 9th or September 6th.

你還需要先掌握其他關鍵的信息。不能使用本機T-SQL來確定6/9/2012是6月9日還是9月6日。

#5


10  

For this problem the best solution I use is to have a CLR function in Sql Server 2005 that uses one of DateTime.Parse or ParseExact function to return the DateTime value with a specified format.

對於這個問題,我使用的最佳解決方案是在Sql Server 2005中使用一個DateTime的CLR函數。解析或解析函數,以返回指定格式的DateTime值。

#6


7  

why not try

為什么不試試

select convert(date,'10/15/2011 00:00:00',104) as [MM/dd/YYYY]

date formats can be found at SQL Server Helper > SQL Server Date Formats

可以在SQL Server Helper > SQL Server日期格式中找到日期格式。

#7


2  

This page has some references for all of the specified datetime conversions available to the CONVERT function. If your values don't fall into one of the acceptable patterns, then I think the best thing is to go the ParseExact route.

此頁面包含對所有指定的轉換函數可用的datetime轉換的引用。如果您的值不屬於可接受的模式之一,那么我認為最好的方法是走精確的路線。

#8


2  

Personally if your dealing with arbitrary or totally off the wall formats, provided you know what they are ahead of time or are going to be then simply use regexp to pull the sections of the date you want and form a valid date/datetime component.

如果您處理的是任意或完全關閉的牆格式,只要您知道它們在時間前面是什么,或者將會簡單地使用regexp來提取您想要的日期的部分,並形成一個有效的日期/日期時間組件。

#9


1  

If you want SQL Server to try and figure it out, just use CAST CAST('whatever' AS datetime) However that is a bad idea in general. There are issues with international dates that would come up. So as you've found, to avoid those issues, you want to use the ODBC canonical format of the date. That is format number 120, 20 is the format for just two digit years. I don't think SQL Server has a built-in function that allows you to provide a user given format. You can write your own and might even find one if you search online.

如果您希望SQL Server嘗試並解決這個問題,只需使用CAST CAST(“whatever”作為datetime),但這通常不是一個好主意。國際日期可能會出現一些問題。因此,如您所發現的,為了避免這些問題,您希望使用日期的ODBC規范格式。這是120格式,20是兩位數年的格式。我不認為SQL Server有一個內置函數,它允許您提供一個用戶給定的格式。你可以自己寫,甚至可以在網上搜索找到。

#10


0  

Use this:

用這個:

SELECT convert(datetime, '2018-10-25 20:44:11.500', 121) -- yyyy-mm-dd hh:mm:ss.mmm

And refer to the table in the official documentation for the conversion codes.

並參閱轉換代碼的官方文檔中的表格。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2008/10/16/725ece286615083d8a48626aba388d98.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com