Need help with C# ParseExact syntax and moving between timezones - c#

Okay, I have decided to let the magic of Stackoverflow work for me!
I have a date in the format: "Apr 18 2011 19:30 EDT" that I need to push into a DateTime object in C#. One caviat, I also want to shift it to UTC too. Obivisouly when DST is over it'll come over as EST.
I know that I need a statement like:
DateTime.ParseExact("Apr 18 2011 19:30 EDT", "MMM DD yyyy something something ", CultureInfo.InvariantCulture, DateTimeStyles.None, out convertedDate);
But getting it over to UTC is above my knowlwedge level.
So in summary, I need:
To turn Apr 18 2011 19:30 EDT into a DateTime
Convert the EDT timezone to UTC time.
End up with a DateTime object.
What's the code, wizards?

Well, if it's always going to be in Eastern Daylight Time, you can do something like:
// Parse string. We don't need escaping since E,D and T
// are not considered special characters by ParseExact.
var dateTimeInEasternTime = DateTime.ParseExact("Apr 18 2011 19:30 EDT",
"MMM dd yyyy HH:mm EDT",
CultureInfo.InvariantCulture);
// Convert from the relevant timezone to UTC.
var dateTimeInUTC = TimeZoneInfo.ConvertTime
(dateTimeInEasternTime,
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"),
TimeZoneInfo.Utc);
You can cache the TimeZoneInfo representing EST (which becomes EDT while daylight savings is on) to prevent the lookup.
If the string could end with a three letter code representing some arbitrary time-zone, it's going to be a lot more difficult since there are many conventions for them, none of which (AFAIK) are currently supported by .NET. Your best bet would be to first build a lookup from the code to the relevant TimeZoneInfo (perhaps through the Id property) after which you can do the conversion with TimeZoneInfo.ConvertTime as usual.

I'm not sure exactly where you're getting hung up. It sounds like you have successfully parsed the string into a DateTime.
To convert the value to UTC, call the ToUniversalTime() method. Note that this will assume the current time value is relative to your system's current time zone.
ToUniversalTime() converts to a DateTime value.

Related

convert datetime string to Utc

how to convert datetime string to utc time format in GMT.
var x = "02/01/2017 10:00";
var z = DateTime.ParseExact(x, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture);
Actually the thing you have tried is wrong, what you can do is, get the DateTime value equivalent to the given date and then convert them to the UTC time, try something like the following:
string inputDateStr = "02/01/2017 10:00";
DateTime inputDate;
if (DateTime.TryParseExact(inputDateStr, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out inputDate))
{
Console.WriteLine("Date time Now : {0} ", inputDate);
Console.WriteLine("Date time UTC : {0} ", inputDate.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"));
}
Working Example
I am not sure what you wanted to do. But, Universal Time, Zulu time, and UTC are effectively modern names for Greenwich Mean Time (GMT). So both the times will be same. You can use the DateTime.ToUniversalTime() or DateTime.UtcNow method to get the UTC time.
It's not completely clear what you are asking... UTC isn't a format, it's a timezone, equivalent to GMT (well, actually that isn't strictly true, but for the purposes of this question it should be ok.
What point in time is your string representing? Is it UTC? Or is it the local time in Moscow? You need to have the answer to that, because they are completely different times.
If the string represents a UTC time, then you can do something like this:
// first parse it to a DateTime object. Notice that the format string corresponds with the string you have - in your code, they were completely different.
var dateTimeWithUnspecifiedKind = DateTime.ParseExact(x, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
So how you have a datetime object. It has a "Kind" property of Unspecified. So it isn't storing any information to specify that it's supposed to be UTC, rather than Moscow or New York time.
// so we do this...
var dateTimeAsUtc = DateTime.SpecifyKind(dateTimeWithUnspecifiedKind, DateTimeKind.Utc);
That means, "keep the numbers the same, but make a note that the datetime is to be interpreted as a UTC datetime".
Then, if you want to convert it back into a string, you can do something like:
var s = dateTimeAsUtc.ToString("O");
Which will give you a nice representation:
2017-01-02T10:00:00.0000000Z
You are lucky you are interested in UTC. The datetime class can only do UTC, "local" (whatever that is), or "Unspecified". It's not super useful for this sort of thing. DateTimeOffset is a bit better - it's basically a DateTime but it also stores the difference between UTC and the offset that's in force at the time.
That may be all you need. If you ever need real clarity around this stuff though, take a look at Noda time - an alternative set of date and time classes for .NET.

How to parse the date and time depends upon the time zone?

I want to parse the string to time.
string inputDate = "1970-01-01T00:00:00+0000";
var dt = DateTime.Parse(inputDate, CultureInfo.InvariantCulture);
Console.WriteLine("Date==> " + dt);
It is working fine in india time(UTC +5.30).
But when I change the time zone to UTC -5 in settings in emulator, the out put is showing
12/31/1969 7:00:00 PM
The date should be same when ever i change the time zone in settings. Please help me to resolve my problem.
Let me explain what is going on here..
Usually, DateTime.Parse method returned DateTime's Kind property will be Unspecified.
But since your string has time zone information and you using DateTime.Parse method without DateTimeStyles overload (it uses DateTimeStyles.None by default), your DateTime's Kind property will be Local.
That's why when you use your code in UTC +05.30 time zone system, it will be generate a result like;
01/01/1970 05:00:00 AM
and when you use in UTC -05.00 time zone system, it will generate;
12/31/1969 7:00:00 PM // which is equal 12/31/1969 19:00:00 AM representation
which is too normal.
The date should be same when ever i change the time zone in settings.
Makind your DateTime as UTC is the best choice in such a case. Using ToUniversalTime() method is one way to do that in a Local time.
From documentation;
The Coordinated Universal Time (UTC) is equal to the local time minus
the UTC offset.
Since your code generates Local time, your ToUniversalTime() generated datetime's will be the same in both time zone.
Another way to do it, using DateTimeStyles.AdjustToUniversal as a third parameter in DateTime.Parse method.
From documentation;
Date and time are returned as a Coordinated Universal Time (UTC). If
the input string denotes a local time, through a time zone specifier
or AssumeLocal, the date and time are converted from the local time to
UTC. If the input string denotes a UTC time, through a time zone
specifier or AssumeUniversal, no conversion occurs. If the input
string does not denote a local or UTC time, no conversion occurs and
the resulting Kind property is Unspecified.
string inputDate = "1970-01-01T00:00:00+0000";
var dt = DateTime.Parse(inputDate,
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal);
That will generate 01/01/1970 00:00:00 which Kind is Utc.
Final Solution
string givenDate = ("1970-01-01T00:00:00+0000");
DateTime d = DateTime.Parse(givenDate, System.Globalization.CultureInfo.InvariantCulture);
string ouputDate = d.ToUniversalTime().ToString("MMM d, yyyy h:m:s tt", System.Globalization.CultureInfo.InvariantCulture);

Troubles parsing DateTime from string

I am currently trying to parse a string that is obtained from an xml that is downloaded from the web every few minutes. The string looks like this:
Thu Jul 12 08:39:56 GMT+0100 2012
At first I just did a string.split and took out everything after the time (GMT+0100 2012) and inserted 2012 after the date.
This worked great until the date changed to:
Thu Jul 12 08:39:56 GMT+0000 2012
So I would like to dynamically pasre the GMT+ whatever as they send me that string in c#.
Any advice would be appreciated.
You can use DateTime.ParseExact with a custom date and time format string:
DateTime.ParseExact("Thu Jul 12 08:39:56 GMT+0000 2012",
"ddd MMM dd hh:mm:ss 'GMT'K yyyy",
CultureInfo.InvariantCulture)
This will throw a format exception if the string and format string do not match exactly, so you may want to use DateTime.TryParseExact that will return a false if it fails.
Instead of DateTime you may want to use DateTimeOffset that preserved timezone information , as #Keith commented - this may be important to your application.
Two things you can do: First, you should be able to use a custom format string with a ParseExact method, either from DateTime or DateTimeOffset (I would use DateTimeOffset if the actual time zone of the stamp is important, and not just the equivalent time in UTC or your local time zone).
Have a look: DateTime custom format string
The format string would probably be something like #"ddd MMM dd HH:mm:ss 'GMT'zzzz yyyy".
However, there's one snag; the .NET time zone offset ("zzzz" or simply "K") always includes a colon between the hour and minute when expressed as a string, which your input strings do not have. There is no way I know of to specify that the time zone offset doesn't/shouldn't have this colon, and I'm pretty sure that trying to parse it without a colon would cause an error.
The simplest workaround is to remove that specific colon from the string prior to parsing it. The code for that given your input is simply to remove the last colon character in the string:
var updatedString = inputString.Remove(inputString.LastIndexOf(':'), 1);
Try DateTime.Parse method to parse your date.
This should work:
XmlConvert.ToDateTime(textBox1.Text, "ddd MMM dd HH:mm:ss 'GMT'zzzz yyyy");

Twitter time to local time c#

How do i convert the time of tweets made by the user to localtime? The created_at gives me the time of the tweet created and is based on the user's country, how to i change it to my localtime using c#. The format of the time is "Fri Jul 27 15:14:11 +0000 2012". What do they mean by utc_offset and how can it be used to change the timezone?
I am not really familiar with the timezone stuff, thank you for your help :)
You'll want to use the DateTimeOffset structure. This allows you to capture a date and a time as well as offset from UTC as well.
The format that you want to use for Twitter times is:
string twitterDate = "Fri Jul 27 15:14:11 +0000 2012";
DateTimeOffset dt = DateTimeOffset.ParseExact(twitterDate,
"ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture);
Note that while not documented, zzzz does work as a custom date time format and succeeds in parsing the offset correctly. This means you should be careful in relying on it in the future (unless the documentation changes to reflect this functionality).
Once you have the DateTimeOffset, you know the offset from UTC. If you want to get it in your local time, you can call the ToLocalTime method on the DateTimeOffset that was parsed and it will return an instance that has an offset based on your local settings.
This should be it:
DateTime localDateTime = DateTime.ParseExact(dateString, "ddd MMM dd HH:mm:ss zzz yyyy", new CultureInfo("en-US"));
Unless you give a DateTimeKind in the constructor of a DateTime, the DateTime will be in the timezone the administrator of the workstation/server has selected for Windows.

Converting UK times (both BST and GMT) represented as strings to UTC (in C#)

I have to use some dates and times from a legacy database. They are represented as strings. Dates are dd/MM/yy. Times are HH:mm.
I'd like to convert these to UTC as soon as I pull them from the database. I'm working on US systems, so need a common time.
The problem I'm facing is how to convert them to UTC DateTime values. I can do the parsing, etc. The real problem I have concerns the timezone.
I'm trying to use the following approach:
DateTime ukTime = // Parse the strings in a DateTime value.
TimeZoneInfo timeZoneInformation = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTimeOffset utcTime = new DateTimeOffset(ukTime, timeZoneInformation.BaseUtcOffset);
However, this gives incorrect values if the date is in the British Summer Time period.
I can use "GMT Daylight Time" on those dates, but that requires me to know when the switchover is. I'm sure there must be a less laborious way.
As I'm not using a machine with UK time settings I can't rely on local time.
Basically, I need something like:
// Works for both GMT (UTC+0) and BST (UTC+1) regardless of the regional settings of the system it runs on.
DateTime ParseUkTimeAsUtcTime(string date, string time)
{
...
}
I've scoured the posts, but couldn't find anything that addressed this directly. Surely this is also an issue with EST, EDT, etc?
Try using the GetUtcOffset() method on your TimeZoneInfo instance, which takes "adjustment rules" into consideration.
Using this should work basically the same as your original example, but you'll use that method instead of the BaseUtcOffset property.
DateTime ukTime = // Parse the strings in a DateTime value.
TimeZoneInfo timeZoneInformation = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTimeOffset utcTime = new DateTimeOffset(ukTime, timeZoneInformation.GetUtcOffset(ukTime));
How about:
DateTime.Parse(dateTimeString).ToUniversalTime();
Assuming that the database server stores its datetimes in the same timezone as your application server.

Categories

Resources