Home > Software design >  Convert unixtime to DateTime immediately
Convert unixtime to DateTime immediately

Time:09-08

There was a problem converting unixtime to DateTime.

I am passing in parameter 1663869600 this is September 22, 22. But in the code, after instrumentation, I get the date 1/20/1970 6:11:09 AM.

Why is that ?

I will convert the date in the following ways:

DateTime start = DateTimeOffset.FromUnixTimeMilliseconds(request.StartTime).DateTime;
var startUtc = DateTime.SpecifyKind(start, DateTimeKind.Utc);

and

DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var startUtc = dtDateTime.AddMilliseconds(request.StartTime).ToLocalTime();

CodePudding user response:

Unix time is number of seconds (not milliseconds) since the epoch (as @Gus correctly mentioned). So the solution is to use FromUnixTimeSeconds instead of FromUnixTimeMilliseconds and AddSeconds instead of AddMilliseconds.

DateTime start = DateTimeOffset.FromUnixTimeSeconds(1663869600).DateTime;
var startUtc = DateTime.SpecifyKind(start, DateTimeKind.Utc);

DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var startUtc2 = dtDateTime.AddSeconds(1663869600).ToLocalTime();
  •  Tags:  
  • c#
  • Related