Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update Only TZoffset in DATETIME column

I have a set of dates like 2023-11-30 23:59:59.0000000 +00:00. I want to update only the time zone offset from +00:00 to +01:00 to all of them.
If it makes things easier, all of the times are 23:59:59.0000000 and only the date differentiates.

I’ve tried this:

UPDATE Table SET Date = DATEADD(DAY, DATEDIFF(DAY, 0, Date), '2023-11-30 23:59:59.0000000 +01:00')

But it only worked with accuracy up to seconds, without milliseconds, nanoseconds and tzoffset. I’ve got this error, when I tried that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Conversion failed when converting date and/or time from character string.

>Solution :

Seems like you want TODATETIMEOFFSET:

DECLARE @YourValue datetimeoffset(7) = '2023-11-30 23:59:59.0000000 +00:00';

SELECT TODATETIMEOFFSET(@YourValue,'+01:00');

This returns 2023-11-30 23:59:59.0000000 +01:00. This works because it takes your datetimeoffset value and (implicitly) converts it to a datetime2 first, which truncates the offset value, and then adds the new offset to the value; thus not changing the actual time and just the offset.

If you’re saying that you actually change the value so that the date and time changes with the offset, then you want SWITCHOFFSET:

DECLARE @YourValue datetimeoffset(7) = '2023-11-30 23:59:59.0000000 +00:00';

SELECT SWITCHOFFSET(@YourValue,'+01:00');

This returns 2023-12-01 00:59:59.0000000 +01:00.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading