GETUTCDATE() and Time Zone (SQL Server)

前端 未结 4 1980
小鲜肉
小鲜肉 2020-12-22 03:30

I want to add my time zone with the function GETUTCDATE() in SQL Server. I searched several times, but did not found any relevant solution. Thanks in advance.

相关标签:
4条回答
  • 2020-12-22 04:07

    Use GETDATE() instead GETUTCDATE(). see this link

    0 讨论(0)
  • 2020-12-22 04:15

    only for sql 2016, it takes into account daylight savings.

    CREATE FUNCTION GetBelgiumTime 
    (
    )
    RETURNS datetime2
    AS BEGIN  
           declare @dateoffset datetimeoffset
           SET  @dateoffset = convert(VARCHAR(2000),(SELECT GETUTCDATE() AT TIME ZONE  'Central European Standard Time'),126 )
    
    
           declare @date datetime2
           set @date = convert(datetime2, LEFT(@dateoffset,28),126)
    
        set @date = DATEADD(HOUR, convert(int,LEFT(RIGHT(@dateoffset,5), 2)), @date) 
           RETURN @date
    END
    
    select  dbo.GetBelgiumTime() as BelgiumDateAndTime 
    
    0 讨论(0)
  • 2020-12-22 04:20

    From SQL Server 2016 forward (and Azure SQL DB), you can do this:

    SELECT SYSDATETIMEOFFSET() AT TIME ZONE @tz
    

    where @tz is a valid Windows time zone identifier, such as 'Pacific Standard Time', 'Central European Standard Time', etc.

    However, if you are on an older version of SQL Server, or prefer to use IANA time zone identifiers, you can use my SQL Server Time Zone Support project to do the following:

    SELECT Tzdb.UtcToLocal(GETUTCDATE(), @tz)
    

    where @tz is an IANA standard time zone name, such as 'America/Los_Angeles' or 'Europe/Budapest'.

    0 讨论(0)
  • 2020-12-22 04:31

    You can try to use switchoffset like this:

    select switchoffset(CAST(myDate as datetimeoffset),'+05:30')  from someTable
    

    Instead of '+05:30' you can specify your timezone value.

    If you want to use the timezone with GETUTCDATE() then simply add it like this

    select cast(GETUTCDATE() as varchar(20)) + '+5:30'
    

    and if you want to keep it as date only then

    select  switchoffset(CAST(GETUTCDATE() as datetimeoffset),'+05:30')
    
    0 讨论(0)
提交回复
热议问题