Home > database >  Compare datetimes ignoring time zone
Compare datetimes ignoring time zone

Time:01-18

I have timestamps from the different timezones and I want to compare times from different timezones ignoring timezone information. Basically, 9AM from one timezone should be equal to 9AM from another timezone in my case. How should I do this in C# in the most natural way?

var dt1 = DateTime.Parse("2022-01-17T18:59:43.0030684 06:00");
var dt2 = DateTime.Parse("2022-01-17T18:59:43.0030684 03:00");

Console.WriteLine(DateTime.Compare(dt1, dt2));

It returns -1 right now, I want something that returns 0.

CodePudding user response:

Try this:

var dt1 = DateTimeOffset.Parse("2022-01-17T18:59:43.0030684 06:00");
var dt2 = DateTimeOffset.Parse("2022-01-17T18:59:43.0030684 03:00");
Console.WriteLine(DateTime.Compare(dt1.DateTime, dt2.DateTime));

CodePudding user response:

Technically, you can use DateTimeOffset instead of DateTime in order to compensate (i.e. add) difference of time zones:

Code:

var dt1 = DateTimeOffset.Parse("2022-01-17T18:59:43.0030684 06:00");
var dt2 = DateTimeOffset.Parse("2022-01-17T18:59:43.0030684 03:00");

Console.WriteLine(DateTimeOffset.Compare(dt1   dt1.Offset, dt2   dt2.Offset));

Outcome: (fiddle)

0
  •  Tags:  
  • Related