0

Tried to cast the datatime object ,which is queried from database. Value is in UTC time. is it affect the local timezone when i tried to cast the object ?

var daytime = (DateTime)reader["day"];

reader["day"] is a object and value is in UTC time. For accessing the value i changed it into DateTime. my intention is i want to convert this value to epoch time.

var daytime = (DateTime)reader["day"];
long epochTicks = new DateTime(1970, 1, 1).Ticks;
long unixTime = ((daytime.Ticks - epochTicks) / TimeSpan.TicksPerSecond);
avancho marchos
  • 180
  • 1
  • 1
  • 9
  • If you can you should store a datetimeoffset in the database. Otherwise if you know it to always be UTC, you can change the DateTimeKind after you cast it. – Silvermind Mar 03 '21 at 13:55
  • @Sinatr i don't want to convert the data. Just cast the data. receiving data in object type.In the example it convert/parse into Datetime?. this is not correct for my case.am i right ? – avancho marchos Mar 03 '21 at 14:03
  • The short answer to your question is *no*. Neither casting from `object` to `DateTime` nor subtracting ticks would be affected by time zone. The code you wrote will work fine. However, you could do this instead: `long unixTime = new DateTimeOffset(daytime, TimeSpan.Zero).ToUnixTimeSeconds();` – Matt Johnson-Pint Mar 07 '21 at 20:51

0 Answers0