How to cast datetimeoffset to datetime in entity framework?

datetimeoffset entity-framework-6

Popular Answer

To remove the offset, use the DbFunctions.CreateDateTime, for instance:

...
.Select(e => new MyClass {                                      
  MyDate = DbFunctions.CreateDateTime(e.MyDateTimeOffset.Year,
                                      e.MyDateTimeOffset.Month,
                                      e.MyDateTimeOffset.Day,
                                      e.MyDateTimeOffset.Hour,
                                      e.MyDateTimeOffset.Minute,
                                      e.MyDateTimeOffset.Second)
...

As you may anticipate, this generates some dreadful SQL, such as:

convert (datetime2,right('000' + convert(varchar(255), DATEPART (year, [Extent1].[MyDateTimeOffset])), 4) + '-' + convert(varchar(255), DATEPART (month, [Extent1].[MyDateTimeOffset])) + '-' + convert(varchar(255), DATEPART (day, [Extent1].[MyDateTimeOffset])) + ' ' + convert(varchar(255), DATEPART (hour, [Extent1].[MyDateTimeOffset])) + ':' + convert(varchar(255), DATEPART (minute, [Extent1].[MyDateTimeOffset])) + ':' + str( CAST( DATEPART (second, [Extent1].[MyDateTimeOffset]) AS float), 10, 7), 121) AS [C2]

You will, however, get what you desire.

One warning is that the offset will be entirely ignored by this (as the OP requested).

1
9/23/2017 3:58:53 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow