我有同样的问题,我想满足 mssql 的日期时间范围
- 最小日期时间:1753-01-01 00:00:00.000 (-6847804800)
- 最大日期时间:9999-12-31 23:59:59.997 (253402300799)
为了实现这一点,我发现的唯一解决方案是循环使用带有 int 范围值的 DATEADD。
所以基于这个答案:https ://stackoverflow.com/a/2904294/687490
CREATE FUNCTION dbo.fn_ConvertToBigDateTime (@Datetime BIGINT)
RETURNS DATETIME
AS
BEGIN
DECLARE @result datetime = Convert(datetime, '01/01/1970');
DECLARE @LocalTimeOffset BIGINT
,@AdjustedLocalDatetime BIGINT
,@MinIntValue INT
,@MaxIntValue INT
,@RemainingSeconds BIGINT;
-- define int limit
SET @MinIntValue = -2147483648;
SET @MaxIntValue = 2147483647;
-- compute the datetime with the offset
SET @LocalTimeOffset = DATEDIFF(second,GETDATE(),GETUTCDATE())
SET @AdjustedLocalDatetime = @Datetime - @LocalTimeOffset
-- going to the future
WHILE(@AdjustedLocalDatetime>@MaxIntValue)
BEGIN
SET @AdjustedLocalDatetime = @AdjustedLocalDatetime - @MaxIntValue;
SELECT @result = Convert(datetime, dateadd(ss, @MaxIntValue,@result));
END
-- going back in the past
WHILE(@AdjustedLocalDatetime<@MinIntValue)
BEGIN
SET @AdjustedLocalDatetime = @AdjustedLocalDatetime - @MinIntValue;
SELECT @result = Convert(datetime, dateadd(ss, @MinIntValue,@result));
END
RETURN (SELECT DATEADD(second,@AdjustedLocalDatetime, @result))
END;
然后,您可以使用以下命令测试该功能:
select dbo.fn_ConvertToBigDateTime(-6847804800) as 'min datetime',
dbo.fn_ConvertToBigDateTime(253402300799) as 'max datetime'
希望它会有所帮助。