📜  sql server utc 到本地 - SQL (1)

📅  最后修改于: 2023-12-03 14:47:35.728000             🧑  作者: Mango

SQL Server UTC to Local

When working with dates and times, it's important to understand time zones and how to convert between them. In SQL Server, dates and times are stored in UTC (Coordinated Universal Time) format, which is a standard time format used worldwide.

However, when displaying dates and times to users, it's often necessary to convert UTC to the local time zone. In this guide, we'll explore different methods for converting UTC to local time in SQL Server.

Using the GETUTCDATE Function

The easiest way to get the current UTC time in SQL Server is by using the GETUTCDATE function. This function returns the current UTC date and time as a datetime2 value.

To convert UTC to local time, you can use the SWITCHOFFSET function. This function converts a datetime2 value from one time zone to another.

-- Get the current UTC time
DECLARE @utc_time datetime2 = GETUTCDATE()

-- Convert UTC to local time (UTC-5)
DECLARE @local_time datetime2 = SWITCHOFFSET(@utc_time, '-05:00')

-- Display the local time
SELECT @local_time

The SWITCHOFFSET function takes two arguments: the datetime2 value to convert, and the offset value to apply. In this example, we're using the offset '-05:00' to convert UTC to the Eastern Time Zone.

Using the AT TIME ZONE Function

Another way to convert UTC to local time in SQL Server is by using the AT TIME ZONE function. This function converts a datetime2 value from one time zone to another, based on the time zone name or abbreviation.

-- Get the current UTC time
DECLARE @utc_time datetime2 = GETUTCDATE()

-- Convert UTC to local time (Eastern Time Zone)
DECLARE @local_time datetime2 = @utc_time AT TIME ZONE 'Eastern Standard Time'

-- Display the local time
SELECT @local_time

The AT TIME ZONE function also takes two arguments: the datetime2 value to convert, and the time zone name or abbreviation. In this example, we're using the 'Eastern Standard Time' time zone to convert UTC to the Eastern Time Zone.

Conclusion

In this guide, we've explored two methods for converting UTC to local time in SQL Server: using the SWITCHOFFSET function, and using the AT TIME ZONE function. These functions can be used to convert UTC to any local time zone, based on the offset or time zone name.

When working with dates and times in SQL Server, it's important to always consider time zones and to ensure that date and time values are displayed in the appropriate time zone for the user.