Muhammad Usama Alam
Muhammad Usama Alam

Reputation: 209

How to Get Total time in Two Date time With Different Time zone in c#

I have to two date time

Datetime d1 = Convert.ToDateTime("2018-03-13T00:30");
Datetime d2 = Convert.ToDateTime("2018-03-14T06:05");

d1 Datetime timezone is "8"
d2 Datetime timezone is "-7"

how i calculate Total Time Between Two Date time.

i am using this code

var calc = (d1 - d2);
var hours = calc.Hours - (d1_timezone - (d2_timezone));

but Hours in (-) negative value

Upvotes: 0

Views: 91

Answers (2)

j4nw
j4nw

Reputation: 2405

You should use DateTimeOffset, which is pretty much DateTime with an explicit Offset property, so it has a concept of time zones. It exists specifically to handle such cases.

var d1 = DateTimeOffset.Parse("2018-03-13T00:30+8");
var d2 = DateTimeOffset.Parse("2018-03-14T06:05-7");
Console.WriteLine((d2 - d1).TotalHours); // -> 44.5833333333333

Upvotes: 1

Liam
Liam

Reputation: 29624

You just need to get the times into a common timezone and then work out the difference:

Datetime d1 = Convert.ToDateTime("2018-03-13T00:30");
Datetime d2 = Convert.ToDateTime("2018-03-14T06:05");

// this is now "2018-03-13T08:30"
Datetime d1Common = d1.AddHours(8);
// this is now "2018-03-13T11:05"
Datetime d2Common = d2.AddHours(-7);

//TimeSpan difference = d1Common - d2Common;
//I'm pretty sure you want the difference this way around.
TimeSpan difference = d2Common - d1Common;
int hoursDifference = difference.TotalHours;
int daysDifference = difference.TotalDays;
//   .....etc.

If those are the correct timezones then the difference between d1 and d2 is going to be negative. d1 happened before d2. Even when you allow for the time difference, I think you maybe want d2Common - d1Common?

Upvotes: 1

Related Questions