at the moment I need to determine what timezone is currently "9am". I have a table to timezones and their offsets plus taking into consideration daylight savings
The offsets are stored in my database as +/- time.
For example, LA/Vancouver is -8:00
The approach I was going to take was to iterate through all time zones, convert the offset so I can addhours and addminutes to DateTime.UtcNow then check if the hour is 9. The only issue I see is that it's not able to handle daylight savings.
I was wondering is there are any existing libraries I can leverage for my scenario or a better approach to the one I suggested? In the end I require the ID column.
Timezones table
This is relatively easy to do using the built-in .NET classes TimeZoneInfo and DateTime, but you might be surprised by the results.
from z in TimeZoneInfo.GetSystemTimeZones()
let timeThere = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, z)
where timeThere.Hour == 9
select new{z.DisplayName, timeThere}
For example, right now there are 7 time zones that my machine is aware of in which it's in the 9 AM hour.
I've seen solutions that make use of the current local timezone. What if I'm looking for the offset of a timezone which is not my own and is currently observing daylight savings time?
Edit:
I realize it is hard to infer exactly what I am asking for.
Currently when a user is set up in the system, they select a timezone. All of our data is converted to this timezone they selected (using the offset).
Example:
A user selects UTC-8, but then travels to somewhere that is UTC-6. We will display data and convert it based on the UTC-8 offset. The problem here being when daylight savings is applied to this timezone, it is effectively UTC-7. Based on the information available, I am able to get a TimeZoneInfo for UTC-8. I know I can extrapolate from the TimeZoneInfo.AdjustmentRule to determine if we are currently observing Daylight Savings, and what the delta is. I am curious if there was something in the framework I am missing that would handle this for me before re-inventing the wheel.
Note: This is a web application. The TimeZoneInfo is gathered on the server side, and pass down the User's offset so we can convert UTC to the user's selected timezone preference. I agree it would be easier if the user's browser client provided their system timezone, however it is not viable (due to business rules) to use the timezone of the browser, as the user wants to see the information based on the timezone they have selected.
You need to use the TimeZoneInfo class. I suspect your question is slightly misphrased. The offset is usually part of the name itself and on its own is not usually a very interesting fact. Its usefulness comes from what you then intend to infer from it.
You may be asking:
Given time X in timezone Y, what time is that in UTC
Given time X in timezone Y, what time is that in my local timezone
Given time X in my timezone, what local time will that be in timezone Y
Here is a starter which gives the first:
public static DateTime ConvertToUtc(DateTime timeOfInterest, string timezoneId)
{
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById(timezoneId);
if (tz.IsInvalidTime(timeOfInterest))
{
// Timezones with DST will be missing (usually) an hour one day a year, so some timeOfInterest
// values are not valid
throw new ArgumentOutOfRangeException($"{timeOfInterest} is not a valid time in {timezoneId} timezone");
}
return TimeZoneInfo.ConvertTimeToUtc(timeOfInterest, tz);
}
You could even do that as an extension method if you wanted.
For those other functions, see also:
tz.IsDaylightSavingTime()
tz.GetUtcOffset()
tz.SupportsDaylightSavingTime
TimeZoneInfo.ConvertTimeFromUtc()
TimeZoneInfo.ConvertTime()
Finally, be aware that these rules change all the time as different jurisdictions change their laws regarding the times that they observe. Make sure whatever system is performing these computations gets its windows updates.
I have a question about DateTimeOffset and daylight savings time. To explain my question lets assume that right now the date and time is:
11/6/2010 10:15:00 AM
If I run this code:
DateTimeOffset myTime = DateTimeOffset.Now;
Console.WriteLine("Local time: " + myTime.ToLocalTime().DateTime);
Then I get this result:
Local time: 11/6/2010 10:15:00 AM
Meaning that the event happened at 10:15 in the morning (my time zone is Mountain Daylight Time (-6 offset)).
So, then I save this DateTimeOffset to my SQL Server 2008 db (as a DateTimeOffset). The next day I want to display it to the user. But now daylight savings has expired.
If I run the above WriteLine with the saved off value (from the previous day) what will display?
The offset stored in the database is -6. But now that daylight savings is over, the current offset is -7. So as I understand the documentation, it will first convert my time to UTC time (so it takes 10:15 AM and adds 6 hours (4:15 pm). It will then subtract the current offset of the local time (4:15 pm - 7 = 9:15 AM).
So if I my math is right, now when I display my event, it will show that it occurred at 9:15 AM rather than 10:15 AM.
This is not good. I want to store time zone information, but I need my times to stay static in the same time zone. (Meaning that if the event happened at 10:15 AM in Utah, then the next time I look at it (in Utah), I need to see that it was at 10:15 AM, regardless if the daylight savings time change has happened.
I can't think I am the first one to have this issue. What do others do to fix this? (Or do I have the facts wrong?)
No, it won't add the current offset - it'll add the offset at that date which is still -6. So it should still display 10:15AM, because it knows the date involved, and thus the time zone rules in force on that date.
You may well want to store a simple UTC time and the time zone identifier separately, by the way. If you're storing a time zone, then using DateTimeOffset won't be particularly helpful over just a UTC date/time. (On the other hand, it's clearer that it does represent an instant in time - DateTime is a horribly confused type which doesn't let you easily express what you're trying to represent.)
Of course I'd personally encourage you to look at Noda Time which in my very biased opinion is a rather clearer date/time API than the built-in one... but which isn't quite ready for production use. (We're getting there though...)
What is the difference between a DateTime and a DateTimeOffset and when should one be used?
Currently, we have a standard way of dealing with .NET DateTimes in a TimeZone-aware way: Whenever we produce a DateTime we do it in UTC (e.g. using DateTime.UtcNow), and whenever we display one, we convert back from UTC to the user's local time.
That works fine, but I've been reading about DateTimeOffset and how it captures the local and UTC time in the object itself.
DateTimeOffset is a representation of instantaneous time (also known as absolute time). By that, I mean a moment in time that is universal for everyone (not accounting for leap seconds, or the relativistic effects of time dilation). Another way to represent instantaneous time is with a DateTime where .Kind is DateTimeKind.Utc.
This is distinct from calendar time (also known as civil time), which is a position on someone's calendar, and there are many different calendars all over the globe. We call these calendars time zones. Calendar time is represented by a DateTime where .Kind is DateTimeKind.Unspecified, or DateTimeKind.Local. And .Local is only meaningful in scenarios where you have an implied understanding of where the computer that is using the result is positioned. (For example, a user's workstation)
So then, why DateTimeOffset instead of a UTC DateTime? It's all about perspective. Let's use an analogy - we'll pretend to be photographers.
Imagine you are standing on a calendar timeline, pointing a camera at a person on the instantaneous timeline laid out in front of you. You line up your camera according to the rules of your timezone - which change periodically due to daylight saving time, or due to other changes to the legal definition of your time zone. (You don't have a steady hand, so your camera is shaky.)
The person standing in the photo would see the angle at which your camera came from. If others were taking pictures, they could be from different angles. This is what the Offset part of the DateTimeOffset represents.
So if you label your camera "Eastern Time", sometimes you are pointing from -5, and sometimes you are pointing from -4. There are cameras all over the world, all labeled different things, and all pointing at the same instantaneous timeline from different angles. Some of them are right next to (or on top of) each other, so just knowing the offset isn't enough to determine which timezone the time is related to.
And what about UTC? Well, it's the one camera out there that is guaranteed to have a steady hand. It's on a tripod, firmly anchored into the ground. It's not going anywhere. We call its angle of perspective the zero offset.
So - what does this analogy tell us? It provides some intuitive guidelines-
If you are representing time relative to some place in particular, represent it in calendar time with a DateTime. Just be sure you don't ever confuse one calendar with another. Unspecified should be your assumption. Local is only useful coming from DateTime.Now. For example, I might get DateTime.Now and save it in a database - but when I retrieve it, I have to assume that it is Unspecified. I can't rely that my local calendar is the same calendar that it was originally taken from.
If you must always be certain of the moment, make sure you are representing instantaneous time. Use DateTimeOffset to enforce it, or use UTC DateTime by convention.
If you need to track a moment of instantaneous time, but you want to also know "What time did the user think it was on their local calendar?" - then you must use a DateTimeOffset. This is very important for timekeeping systems, for example - both for technical and legal concerns.
If you ever need to modify a previously recorded DateTimeOffset - you don't have enough information in the offset alone to ensure that the new offset is still relevant for the user. You must also store a timezone identifier (think - I need the name of that camera so I can take a new picture even if the position has changed).
It should also be pointed out that Noda Time has a representation called ZonedDateTime for this, while the .Net base class library does not have anything similar. You would need to store both a DateTimeOffset and a TimeZoneInfo.Id value.
Occasionally, you will want to represent a calendar time that is local to "whomever is looking at it". For example, when defining what today means. Today is always midnight to midnight, but these represent a near-infinite number of overlapping ranges on the instantaneous timeline. (In practice we have a finite number of timezones, but you can express offsets down to the tick) So in these situations, make sure you understand how to either limit the "who's asking?" question down to a single time zone, or deal with translating them back to instantaneous time as appropriate.
Here are a few other little bits about DateTimeOffset that back up this analogy, and some tips for keeping it straight:
If you compare two DateTimeOffset values, they are first normalized to zero offset before comparing. In other words, 2012-01-01T00:00:00+00:00 and 2012-01-01T02:00:00+02:00 refer to the same instantaneous moment, and are therefore equivalent.
If you are doing any unit testing and need to be certain of the offset, test both the DateTimeOffset value, and the .Offset property separately.
There is a one-way implicit conversion built in to the .Net framework that lets you pass a DateTime into any DateTimeOffset parameter or variable. When doing so, the .Kind matters. If you pass a UTC kind, it will carry in with a zero offset, but if you pass either .Local or .Unspecified, it will assume to be local. The framework is basically saying, "Well, you asked me to convert calendar time to instantaneous time, but I have no idea where this came from, so I'm just going to use the local calendar." This is a huge gotcha if you load up an unspecified DateTime on a computer with a different timezone. (IMHO - that should throw an exception - but it doesn't.)
Shameless Plug:
Many people have shared with me that they find this analogy extremely valuable, so I included it in my Pluralsight course, Date and Time Fundamentals. You'll find a step-by-step walkthrough of the camera analogy in the second module, "Context Matters", in the clip titled "Calendar Time vs. Instantaneous Time".
From Microsoft:
These uses for DateTimeOffset values are much more common than those for DateTime values. As a result, DateTimeOffset should be considered the default date and time type for application development.
source: "Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo", MSDN
We use DateTimeOffset for nearly everything as our application deals with particular points in time (e.g. when a record was created/updated). As a side note, we use DATETIMEOFFSET in SQL Server 2008 as well.
I see DateTime as being useful when you want to deal with dates only, times only, or deal with either in a generic sense. For example, if you have an alarm that you want to go off every day at 7 am, you could store that in a DateTime utilizing a DateTimeKind of Unspecified because you want it to go off at 7am regardless of DST. But if you want to represent the history of alarm occurrences, you would use DateTimeOffset.
Use caution when using a mix of DateTimeOffset and DateTime especially when assigning and comparing between the types. Also, only compare DateTime instances that are the same DateTimeKind because DateTime ignores timezone offset when comparing.
DateTime is capable of storing only two distinct times, the local time and UTC. The Kind property indicates which.
DateTimeOffset expands on this by being able to store local times from anywhere in the world. It also stores the offset between that local time and UTC. Note how DateTime cannot do this unless you'd add an extra member to your class to store that UTC offset. Or only ever work with UTC. Which in itself is a fine idea btw.
This piece of code from Microsoft explains everything:
// Find difference between Date.Now and Date.UtcNow
date1 = DateTime.Now;
date2 = DateTime.UtcNow;
difference = date1 - date2;
Console.WriteLine("{0} - {1} = {2}", date1, date2, difference);
// Find difference between Now and UtcNow using DateTimeOffset
dateOffset1 = DateTimeOffset.Now;
dateOffset2 = DateTimeOffset.UtcNow;
difference = dateOffset1 - dateOffset2;
Console.WriteLine("{0} - {1} = {2}",
dateOffset1, dateOffset2, difference);
// If run in the Pacific Standard time zone on 4/2/2007, the example
// displays the following output to the console:
// 4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00
// 4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00
The most important distinction is that DateTime does not store time zone information, while DateTimeOffset does.
Although DateTime distinguishes between UTC and Local, there is absolutely no explicit time zone offset associated with it. If you do any kind of serialization or conversion, the server's time zone is going to be used. Even if you manually create a local time by adding minutes to offset a UTC time, you can still get bit in the serialization step, because (due to lack of any explicit offset in DateTime) it will use the server's time zone offset.
For example, if you serialize a DateTime value with Kind=Local using Json.Net and an ISO date format, you'll get a string like 2015-08-05T07:00:00-04. Notice that last part (-04) had nothing to do with your DateTime or any offset you used to calculate it... it's just purely the server's time zone offset.
Meanwhile, DateTimeOffset explicitly includes the offset. It may not include the name of the time zone, but at least it includes the offset, and if you serialize it, you're going to get the explicitly included offset in your value instead of whatever the server's local time happens to be.
There's a few places where DateTimeOffset makes sense. One is when you're dealing with recurring events and daylight savings time. Let's say I want to set an alarm to go off at 9am every day. If I use the "store as UTC, display as local time" rule, then the alarm will be going off at a different time when daylight savings time is in effect.
There are probably others, but the above example is actually one that I've run into in the past (this was before the addition of DateTimeOffset to the BCL - my solution at the time was to explicitly store the time in the local timezone, and save the timezone information along side it: basically what DateTimeOffset does internally).
TLDR if you don't want to read all these great answers :-)
Explicit:
Using DateTimeOffset because the timezone is forced to UTC+0.
Implicit:
Using DateTime where you hope everyone sticks to the unwritten rule of the timezone always being UTC+0.
(Side note for devs: explicit is always better than implicit!)
(Side side note for Java devs, C# DateTimeOffset == Java OffsetDateTime, read this: https://www.baeldung.com/java-zoneddatetime-offsetdatetime)
DateTime.Now
Fri 03 Dec 21 18:40:11
DateTimeOffset.Now
Fri 03 Dec 21 18:40:11 +02:00
So, DateTimeOffset stores information about how the time relates to UTC, basically the time zone.
A major difference is that DateTimeOffset can be used in conjunction with TimeZoneInfo to convert to local times in timezones other than the current one.
This is useful on a server application (e.g. ASP.NET) that is accessed by users in different timezones.
The only negative side of DateTimeOffset I see is that Microsoft "forgot" (by design) to support it in their XmlSerializer class. But it has since been added to the XmlConvert utility class.
XmlConvert.ToDateTimeOffset
XmlConvert.ToString
I say go ahead and use DateTimeOffset and TimeZoneInfo because of all the benefits, just beware when creating entities which will or may be serialized to or from XML (all business objects then).
I am consuming the international weather forecasts via Wunderground's XML API:
http://wiki.wunderground.com/index.php/API_-_XML
Looking at an output for Kabul, Afghanistan for instance:
http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query=OAKB
I notice that there is no UTC offset. The closest that I can see is this:
<tz_short>AFT</tz_short>
Which identifies the current TimeZone is AFT. The problem I see is that there is no universally accepted time zone abbreviations, so I cannot take these abbreviations and look up and offset from C#'s TimeZoneInfo objects.
Is there a listing of Wunderground's Time Zones abbreviations/names/offsets so I can map their Time Zones to the TimeZoneInfo objects, or is there a better way to get this information? I will need to use the TimeZoneInfo so I can calculate daylight savings time for different locations internationally.
Here is an idea of what you can do to acquire a UTC offset.
Use the epoch field from the XML output, which will be in UNIX time (number of seconds since 1970-01-01 00:00). This time will be in UTC/GMT. Then, either by converting the contents of the pretty field, or by using the day/month/year/hour/minute/second fields, determine the difference between the published local time and the epoch time. This will give you your UTC offset. There is also a isdst field to tell you whether or not the zone is honoring DST at the moment.
Unfortunately I don't know of a comprehensive list of time zone abbreviations, so using the method above to determine the offset and DST is probably your best option. Good luck!