SQL Server SQL datetimeoffset to datetime

bpzcxfmw  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(96)

I have a datetime column in a table which is in GMT.
I'm trying to convert this using the AT TIME ZONE function to PST. I can do this but I need the result to be as datetime only not with the datetimeoffset .

SELECT MyTableMyDateColumn AT TIME ZONE 'GMT Standard Time' AT TIME ZONE 'Pacific Standard Time' AS 'OrderDate' 
FROM MyTable;

I've tried format as below as well:

SELECT FORMAT(MyTableMyDateColumn , 'MM-dd-yyyy HH:mm:ss') at TIME ZONE 'GMT Standard Time' at TIME ZONE 'Pacific Standard Time'
FROM MyTable

Appreciate all pointers and suggestions

cyvaqqii

cyvaqqii1#

A simple cast to datetime should do the trick.

Create and populate sample table (Please save us this step in your future questions):

CREATE TABLE MyTable 
(
  MyTableMyDateColumn DateTime
);

INSERT INTO MyTable (MyTableMyDateColumn) VALUES 
(GETUTCDATE()), 
(GETDATE());

The query:

SELECT MyTableMyDateColumn,
       MyTableMyDateColumn AT TIME ZONE 'GMT Standard Time' As GMT, 
       MyTableMyDateColumn AT TIME ZONE 'Pacific Standard Time' AS PST,
       -- doing "at time zone" twice is redundant, as you can see in the results
       MyTableMyDateColumn AT TIME ZONE 'GMT Standard Time' AT TIME ZONE 'Pacific Standard Time' AS OrderDate, 
       CAST (MyTableMyDateColumn AT TIME ZONE 'Pacific Standard Time' As DATETIME) As PSTDateTime
FROM MyTable;

Results:

MyTableMyDateColumnGMTPSTOrderDatePSTDateTime
2023-12-06 10:07:39.0572023-12-06 10:07:39.057 +00:002023-12-06 10:07:39.057 -08:002023-12-06 02:07:39.057 -08:002023-12-06 10:07:39.057
2023-12-06 10:07:39.0572023-12-06 10:07:39.057 +00:002023-12-06 10:07:39.057 -08:002023-12-06 02:07:39.057 -08:002023-12-06 10:07:39.057

See a live demo on db<>fiddle

相关问题