Convert GMT Diff to .Net timezone? - c#

My database has GMT Diff for every country like GMT+02:00 and GMT-04:00
Using C# .net is there a simple way to convert that to an actual an .Net timezone?
e.g. "Eastern Standard Time" or "E. Australia Standard Time"
thanks

You can find a timezone, just not that likely the one you want. The UTC offset is ambiguous. GMT+02:00 is the offset for
Jordan Standard Time
GTB Standard Time
Middle East Standard Time
Egypt Standard Time
Syria Standard Time
South Africa Standard Time
FLE Standard Time
Israel Standard Time
E. Europe Standard Time
Any you like in particular? You'd get them with an expression like this:
public static TimeZoneInfo[] GetTimeZones(TimeSpan offset) {
return TimeZoneInfo.GetSystemTimeZones().Where(z => z.BaseUtcOffset == offset).ToArray();
}
I had to look some of these up. FLE = Finland, Lithuania, Estonia. GTB is tougher, I'm guessing at Greece, Turkey, Bulgaria.

That's not going to be possible because different time zones can share the same offset from GMT (or UTC to be more correct).

If you're expecting "Eastern Standard Time" out of it, you need more information than just the offset from GMT. For example, GMT-5 is Eastern Standard Time, Central Daylight Time, Eastern Standard Time (Indiana), and various South American time zones, both with and without Daylight Saving, and on a different DST schedule than the US.

If you are ok with just the first available TimeZone which matches that GMT offset, that should be easy.
This is off my head but...
TimeZoneInfo getTimeZone(string gmtstring)
{
foreach(TimeZoneInfo ti in TimeZoneInfo.GetSystemTimeZones())
{
TimeSpan tsp = ti.BaseUtcOffset;
if(tsp.ToString((tsp.TotalMinutes < 0 ? "-" : "+")+"hh:mm") == gmtstring.Substring(3))
return ti;
}
return null;
}
Otherwise there's no direct relation between timezones and GMT offsets (there are many timezones on the same GMT offset, as the others said)
PS: gmtstring should be in the "GMT(+|-)HH:SS" format

Related

How to use Standard Time Only in TimezoneInfo.ConvertTime C#

I am having a Issue with the C# function of TimeZoneInfo.ConvertTime().
What i need to get is the Standard Time not the DST but i'm only getting DST is there a way to Tell the Function to only get the Result in Standard Time.
My local Timezone is UTC -6:00 Central America Standard Time, so if my time is 12:00 PM the Conversion i'm getting is throwing it at 2 PM Eastern Time but i need it to tell me it's 1:00 PM.
public static DateTime TimetoEst( DateTime timenow)
{
var currentTimeZone = TimeZone.CurrentTimeZone.GetUtcOffset(timenow).ToString();
var estzone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
var conver = TimeZoneInfo.ConvertTime(timenow, estzone);
return conver;
}
Thanks
A couple of things:
The ID "Eastern Standard Time" represents both EST and EDT, with the appropriate transitions in place. It would more appropriately be called "Eastern Time", but alas this is the identifier and the convention used by Windows time zones.
The Eastern Time zone really does transition in and out of daylight saving time. If you were to always adjust to just Eastern Standard Time (UTC-5), you would be ignoring the reality of timekeeping in that region - that it is in Eastern Daylight Time (UTC-4) for dates in the summer months.
Your code will indeed return EST, but only for date values that are outside of the DST period.
Now, if you still think this is what you want to do - then you can do it without the TimeZoneInfo object at all. Simply adjust the result from the offset that applies to your source value, to the UTC-5 offset that applies to EST.
public static DateTime TimetoEst(DateTime timenow)
{
var dto = new DateTimeOffset(timenow); // will use .Kind to decide the offset
var converted = dto.ToOffset(TimeSpan.FromHours(-5));
return converted.DateTime;
}
This is what you asked, but for the record - I don't think this is the best plan. Besides the issues above - assuming that the input value should be interpreted based on the local time zone is not necessarily a good idea - and unless the input time has a .Kind of DateTimeKind.Utc, it will indeed use the computer's local time zone.
You did label the variable as timenow. If you are just after a DateTime which represents the current time in a fixed offset, then it's much safer just to get it like so:
DateTime dt = DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(-5)).DateTime;
And if you really want the current time in the Eastern Time zone, taking DST into account when appropriate, then:
DateTime dt = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow,
"Eastern Standard Time");

What does DateTimeOffset.Now.Offset.ToString() return when in daylight savigs time in the UK

so I know the function DateTimeOffset.Now.Offset returns the offset from UTC and from wikipedia it states that GMT and UTC are the same. Therefore I would guess that DateTimeOffset.Now.Offset.ToString() would always return 00:00:00 if your timezone is (UTC) London. Am I correct in thinking this or would it return 01:00:00 when in daylight savings time?
DateTimeOffset.Now.Offset.ToString() would always return 00:00:00 if
your timezone is UTC.
Right. From documentation of DateTimeOffset.Offset property;
The difference between the current DateTimeOffset object's time value
and Coordinated Universal Time (UTC).
As you can see, it is normal to get 00:00:00 since London is UTC±00:00 which is what we are expected.
Am I correct in thinking this or would it return 01:00:00 when in
daylight savings time?
Exactly. From Wikipedia page of Daylight saving time;
Typically, users of DST adjust clocks forward one hour near the start
of spring and adjust them backward in the autumn to "normal" or
regular time.
By the way, you can't change your offset value with creating a Datetime which it is in your daylight saving time. OffSet value can be change only with changing your time zone manually or with daylight saving time. Your DateTimeOffset still has the same offset value even if you create it when times that daylight saving time.
Yes, UTC and GMT are the same. Just "GMT" term are not using most of computer science community.

Get eastern time in c# without converting local time

I know there are bunch of solutions on converting timezone to timezone, but what I'd like to know whether we can get eastern time without making conversion from our local time.
Well yes and no, if you represent using GMT always then you don't need to convert until you need to show locality.
Time is always in GMT and services should run under the GMT Timezone because of this reason among others.
Receiving and Storing a time in anything other than GMT / UTC requires conversions.
Please note the Timezone of the server should also be set to GMT for things to work as I indicated.
When you set things up like this it thus becomes much easier to reference and compare times and dates in different calendar date formats also.
This is the reason why DateTime offset made its way into the framework and sql server. if not careful when the Timezone on a server changes so does all stored and loaded dates in local format.
A date comparison is a date comparison. DateTime just wraps a memory structure which is defined in ticks and makes methods to access commonly used parts of the memory e.g. day or year or Time or TimeOfDay etc.
Furthermore conversion is only possible if you know both the source and destination offsets and then the calculation is always as given is given by -1 * (sourceOffset - destOffset)
Where the part in parenthesis represents the time zone difference.
Where the DateTime you want to convert is in UTC and called theDate
DateTime eastern = TimeZoneInfo
.ConvertTimeFromUtc(
theDate,
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"))
If theDate has a Kind of Local this will throw, only accepting Kind values of Utc or Unspecified. Of course, moving from local to UTC is easy and we could even check and do this conversion when required, but since you say you want this conversion "without making conversion from our local time" I'm assuming you have your times in UTC and hence having the exception would be better as it would warn you that times that should be UTC are being treat as local and a bug could pop up elsewhere.
This will use Eastern Daylight Time when theDate is a time when EDT is in effect, as that is the normal rule for EST. To use EST even when it is the summer you can create your own TimeZoneInfo:
TimeZoneInfo
.ConvertTimeFromUtc(
theDate,
TimeZoneInfo.CreateCustomTimeZone(
"Eastern Standard Time No Daylight Savings",
new TimeSpan(-5, 0, 0),
"Eastern Standard Time No Daylight Savings",
"Eastern Standard Time No Daylight Savings"))

Convert same time to different time zone

I am trying to convert times to different time zones, but not the way you're thinking. I need to convert a DateTime that is 9am EST to 9am CST on the UTC for example. The timezones are variable so just adding/subtracting hours doesn't seem correct way to do it with NodaTime
Fri, 21 Feb 2014 21:00:00 EST = 1393034400 Epoch Timestamp
convert to
Fri, 21 Feb 2014 21:00:00 CST = 1393030800 Epoch Timestamp
If I understand the question correctly, it sounds like you're trying to convert a date/time in one time zone to another one that has the same local time and a different time zone; that is, a different point in time.
You can do this with Noda Time by combining the LocalDateTime with the new zone. For example, given something like the following:
Instant now = SystemClock.Instance.Now;
DateTimeZone eastern = DateTimeZoneProviders.Tzdb["America/New_York"];
ZonedDateTime nowEastern = now.InZone(eastern);
nowEastern is the time now in the America/New_York time zone. If we print nowEastern directly to the console, we'll see something like 2014-02-22T05:18:50 America/New_York (-05).
As an aside, "EST" and "CST" aren't time zones: they're non-unique abbreviations for a particular offset within a time zone; America/New_York and America/Chicago are probably representative of what we think of as "Eastern" and "Central", though (or you could use something like UTC-05:00 if you really wanted EST even when daylight savings time was in effect).
Given a ZonedDateTime in any time zone, we can convert it to a ZonedDateTime with the same local time and a specified time zone as follows:
DateTimeZone central = DateTimeZoneProviders.Tzdb["America/Chicago"];
ZonedDateTime sameLocalTimeCentral = nowEastern.LocalDateTime.InZoneStrictly(central);
This gives us a ZonedDateTime with the same local time, but a different time zone. With the input above, the result would be 2014-02-22T05:18:50 America/Chicago (-06).
Note that I'm using InZoneStrictly. This will throw an exception if the local time is ambiguous or invalid (for example, during daylight savings transitions). If that's unacceptable, you could use InZoneLeniently, which picks the earliest valid ZonedDateTime on or after the given local time, or InZone, which allows you to specify your own rules in those cases.
On Msdn website you can find all you need.
Small example:
DateTime dateNow = DateTime.Now;
Console.WriteLine("The date and time are {0} UTC.",
TimeZoneInfo.ConvertTimeToUtc(dateNow));
Go to the link for more details on what you want, I can't give you more with that small description

Apply DateTime offset to US Eastern Timezone

I have a page that generates vCal and iCal files to import events into Outlook and iCal. These mail clients (Outlook & iCal) will take in the dates in UTC since they know the user's offset and will handle putting in the right times. Our client for which we're writing this code is based out of the USA Eastern time zone and so am I. Their host is in the Central time zone (1 hour behind Eastern). I'd like to make the code handle this without any hard-coded offsets. My code currently get's the DateTime from our CMS and converts to UTC for Outlook/iCal. That means the DateTime value from the CMS is relative to the hosting location:
// Start Date Time
sb.AppendFormat("DTSTART:{0}\n", thisEvent.StartDate.ToUniversalTime().ToString("yyyyMMddTHHmmssZ"));
When I run this on my local, it's all fine, because the DateTime in the CMS is based on our client's Eastern time zone and so am I, so the process is Eastern -> UTC -> into Outlook which then goes UTC -> Eastern, and everything is good. When I deploy to the server in Central, the DateTime from the CMS is an hour off from Eastern. How can I automatically get the offset from Eastern and add it in before I convert to UTC? I obviously need this to handle both standard time (EST) and daylight time (EDT). I'd like to do it programatically without hard-coded values so it always works correctly no matter what time zone you're in. I.e. if I deliver this code to someone for development in India, it should automatically handle their local server's offset and adjust accordingly.
I need to do something like this where I apply an offset to Eastern time before converting to UTC:
sb.AppendFormat("DTSTART:{0}\n", thisEvent.StartDate.ApplyEasternOffset().ToUniversalTime().ToString("yyyyMMddTHHmmssZ"));
Sorry if this is a topic that's been discussed before, I'm just not sure of the best terms to find a question like this. Thanks in advance.
Check out the TimeZoneInfo class. It has methods to get UTC offsets for any timezone.
http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx
Also, check out this previous post: How to use TimeZoneInfo to get local time during Daylight Savings Time?
Here's an example showing a conversion from Pacfic to Eastern:
var eastern = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
var local = TimeZoneInfo.Local; // PDT for me
Console.WriteLine(DateTime.Now.Add(eastern.BaseUtcOffset - local.BaseUtcOffset));
Shows 4/4/2011 12:05:31 when my local clock shows 9:05:31.
You can use TimeZoneInfo Class.
Take a look at this sample:
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time");
TimeSpan offset = tzi.GetUtcOffset(DateTime.Now);
DateTime testDateTime = DateTime.Now.Add(offset);

Categories