I have a requirement to store Local time(10:31:00) to UTC(04:31:09) in the SQL Server.
I have used the below query to get the desired result.
I have combined @VitalReadingDate='2024-01-11' and local time (10:31:00) to get UTC Time (04:31:09), but it returns Local time not converting in UTC
CONVERT(datetime2,
CONVERT(varchar, @VitalReadingDate) + ' ' + CONVERT(varchar, @VitalReadingTime)
) AT TIME ZONE 'UTC',
As already mentioned in the comments, you need to also specify your local time zone if you want to convert between time zones.
I know the syntax looks a bit silly but I didn't write the rules - so it's something like this:
To get a list of time zone names you can query the system table called
time_zone_info:which will give you a list like this (very partial):
Also, Based on your code I'm assuming
@VitalReadingDateand@VitalReadingTimeare variables of typesDateandTimerespectively - so you should be aware there's a better way to combine them to aDateTime2value - which is to convert them to their binary values, combine these values and then convert that toDateTime2:Please note that the order here is critical. The
+operator here is concatenation, not addition, so if you do the date before the time you'll get an error:For more information, read Jeff Moden's Combine DATE and TIME to DATETIME2 in SQL Server article on SQLServerCentral.
To some up - here's a complete example:
Which results in this:
*I've based my assumption of your local time zone based on the 6 hours difference from UTC
You can see a live demo on db<>fiddle