Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hours elapsed between two times, irrespective of country and time zones

how can we determine the hours elapsed between two times. For example:

3:30PM in San Francisco and 7:30PM in Dubai

The part that I am unclear is that, is there a universal way of calculating the subtracted timespan, by taking time zones and countries in to account.

I am using C# as a primary language. Any help will be deeply appreciated.

Thanks in advance.

like image 809
user153410 Avatar asked Sep 08 '14 06:09

user153410


2 Answers

You asked about:

"3:30PM in San Francisco and 7:30PM in Dubai"

If all you know is the time and location, then you have a problem because not all time zones are fixed entities. Dubai is fixed at UTC+4, but San Francisco alternates between UTC-8 for Pacific Standard Time and UTC-7 for Pacific Daylight Time. So a date is also required to make this conversion.

The following will give you the difference using the current date in the first time zone:

TimeZoneInfo tz1 = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
TimeZoneInfo tz2 = TimeZoneInfo.FindSystemTimeZoneById("Arabian Standard Time");

DateTime today = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tz1).Date;

DateTime dt1 = new DateTime(today.Year, today.Month, today.Day, 15, 30, 0); // 3:30 PM
DateTime dt2 = new DateTime(today.Year, today.Month, today.Day, 19, 30, 0); // 7:30 PM

TimeSpan elapsed = TimeZoneInfo.ConvertTimeToUtc(dt1, tz1) -
                   TimeZoneInfo.ConvertTimeToUtc(dt2, tz2);

(Note that the ID "Pacific Standard Time" is the Windows time zone identifier for the US Pacific Time zone, and despite the name, covers both PST and PDT.)

But even this is not necessarily the best approach because "today" isn't the same in all time zones. At (almost) any point in time, there are two different days in operation worldwide. This illustration from Wikipedia demonstrates this well.

                                                        Date Animation

It's possible that the "current" date for the source time zone is not the same date currently in the end time zone. Without additional input, there's not much you can do about that. You need to know the date in question for each value.

like image 73
Matt Johnson-Pint Avatar answered Sep 27 '22 01:09

Matt Johnson-Pint


If you use the type DateTimeOffset you can avoid some of the pitfalls of using local time because it can represent the local time in any time zone:

var dateTimeOffsetSanFrancisco = DateTimeOffset.Parse("9/8/2014 3:30PM -0700");
var dateTimeOffsetDubai = DateTimeOffset.Parse("9/8/2014 7:30PM +0400");
var elapsedHours = (dateTimeOffsetDubai - dateTimeOffsetSanFrancisco).TotalHours;
like image 41
Martin Liversage Avatar answered Sep 26 '22 01:09

Martin Liversage