简体   繁体   English

转换为日期的最佳方法

[英]Optimal way to convert to date

I have legacy system where all date fields are maintained in YMD format. 我有旧系统,其中所有日期字段均以YMD格式维护。 Example: 例:

20101123
this is date: 11/23/2010

I'm looking for most optimal way to convert from number to date field. 我正在寻找从数字转换为日期字段的最佳方法。

Here is what I came up with: 这是我想出的:

declare @ymd int

set @ymd = 20101122

select @ymd, convert(datetime, cast(@ymd as varchar(100)), 112)

This is pretty good solution but I'm wandering if someone has better way doing it 这是一个很好的解决方案,但是我在徘徊,如果有人有更好的方法

try this: 尝试这个:

CONVERT(DATETIME, CONVERT(NVARCHAR, YYYYMMDD))

For example: 例如:

SELECT CONVERT(DATETIME, CONVERT(NVARCHAR, 20100401))

Results in: 结果是:

2010-04-01 00:00:00.000

What you have is a pretty good soltuion. 您所拥有的是相当不错的解决方案。

Why are you looking for a better way? 您为什么要寻找更好的方法?

我正好用它,对我来说一直很好

As it is stored as an integer then you could potential extract the year, month and day by dividing by 100, 1000. 由于将其存储为整数,因此可以通过除以100、1000来提取年,月和日。

eg 例如

DECLARE @Date INT
SET @Date = 20100401

DECLARE @Year INT
DECLARE @Month INT
DECLARE @Day INT

SET @Year = @Date / 10000
SET @Month = (@Date - (@Year * 10000)) / 100
SET @Day = @Date - (@Year * 10000) - (@Month * 100)

SELECT @Date, DATEADD(MONTH,((@Year-1900)*12)+@Month-1,@Day-1)

However, I have no idea if that is faster than the string comparison you already have. 但是,我不知道这是否比您已有的字符串比较要快。 I think your solution is far cleaner and easier to read and would stick with that. 我认为您的解决方案更加简洁,易于阅读,并且会坚持下去。

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

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