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.
You asked about:
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:
(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.
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.
The simplest way is to convert both DateTime objects to UTC and then subtracting them:
Assuming that Dubai > San Francisco.
To get the total hours elapsed use:
Please note that this will apparently only work for the local computer's time zone. See http://msdn.microsoft.com/en-us/library/system.timezoneinfo(v=vs.110).aspx for a better way to do this.
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: