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");
Related
How do you parse the default git format to a DateTime in C#?
As per What is the format for --date parameter of git commit
The default date format from git looks like Mon Jul 3 17:18:43 2006 +0200.
Right now I don't have control over the output, this strings comes from another tool that printed the date and I need to parse it.
I wouldn't parse this to DateTime, I would parse it to DateTimeOffset since it has a UTC offset value inside of it.
Why? Because if you parse it to DateTime, you will get a DateTime as Local and it might generate different results for different machines since they can have timezone offsets of that time.
For example, I'm in Istanbul and we use Eastern European Time which use UTC+02:00. If I run the example of your code with ParseExact method, I will get the 07/03/2006 18:18:43 as a Local time.
Why? Because in 3 July 2006, my timezone was in a daylight saving time which is UTC+03:00. That's why it generates 1 hour forwarded result. That's the part makes it ambiguous when you parse it to DateTime.
string s = "Mon Jul 3 17:18:43 2006 +0200";
DateTimeOffset dto;
if (DateTimeOffset.TryParseExact(s, "ddd MMM d HH:mm:ss yyyy K",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dto))
{
Console.WriteLine(dto);
}
Now, you have a DateTimeOffset as 07/03/2006 17:18:43 +02:00. You can still get the DateTime part with it's .DateTime property but it's Kind will be Unspecified in that case.
But of course, I suggest to use Noda Time instead which can solve most of the DateTime weirdness.
So far the best format string I found is ddd MMM d HH:mm:ss yyyy K.
DateTime date;
DateTime.TryParseExact(
gitDateString,
"ddd MMM d HH:mm:ss yyyy K",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date
);
This is a very strange date fromat I have never seen before coming back from some API in JSON.
"Tue Aug 04 2015 00:17:38 GMT+0000 (UTC)"
That is generating the following error:
System.FormatException: String was not recognized as a valid DateTime.
Which is understandable when using the following method to parse:
DateTime.Parse(x.process_date.Value)
Anyone dealt with complex date formats that may know how to parse that?
You can use the DateTime.ParseExact method (or DateTime.TryParseExact, to cleanly handle parsing failures) to accomplish this. These methods allow you to explicitly specify the format string.
Something like this could work:
var dateString = "Tue Aug 04 2015 00:17:38 GMT+0000 (UTC)";
var format = "ddd MMM dd yyyy HH:mm:ss GMT+0000 (UTC)";
var parsed = DateTime.ParseExact(
dateString,
format,
System.Globalization.CultureInfo.InvariantCulture);
Or, using TryParseExact:
DateTime parsed;
if (DateTime.TryParseExact(
dateString,
format,
System.Globalization.CultureInfo.InvariantCulture,
DateTimeStyles.None,
out parsed)
{
// parsing was successful
}
else
{
// parsing failed
}
Here's a breakdown of the format string used here:
ddd - The abbreviated name of the day of the week.
MMM - The abbreviated name of the month.
dd - The day of the month, from 01 through 31.
yyyy - The year as a four-digit number.
HH:mm:ss - The hour, using a 24-hour clock from 00 to 23; the minute, from 00 through 59; and the second, from 0 through 59 (delimited by : characters).
GMT+0000 (UTC) - just static text that the format string assumes will always be present. This is pretty brittle and could cause your parsing to fail if the API ever returns different text here. Consider truncating this text, or using NodaTime which offers great support for time zones.
You might need to tweak this format string slightly to your usage -- for example, it wasn't clear from your question whether or not you are using a 12-hour clock or a 24-hour clock.
For more information on how to build a format string, see Custom Date and Time Format Strings on MSDN.
Alternatively, you could eschew using System.DateTime in favor of NodaTime. I'm less familiar with NodaTime myself, but great documentation is available both here on StackOverflow and on NodaTime's site.
I have a string "11 Jan 2011" which I want to convert to the datatype date (i.e 11 Jan 2011).
I have tried all resources about datetime.parse, datetime.parse exact but all these things gives me the same output 2011/01/11 12:00:00 AM. I really don't understand this behaviour. I tried the following:
1.DateTime date = DateTime.Parse("11 Jan 2011");
2.DateTime date = DateTime.ParseExact("11 Jan 2011" , #"dd MMM yyyy", System.Globalization.CultureInfo.InvariantCulture);
parsing and displaying are not the same thing
you parse the original string to a DateTime object but display results using Date/Time format strings
Both your calls are correct.
A DateTime structure preserves no information about formatting; it just represents the raw date and time.
What you need to do is ensure that when you display your date, you do so in the correct format - e.g. by calling string displayString = date.ToString("dd MMM yyyy");
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.
I'd like to convert a bunch of date strings like the following Mon Aug 7 15:32:52 GMT+0900 2007
to
C# datetime objects.
Is there anything built in to the .net framework to do this or will I have to parse the string into date parts?
Many thanks,
You could use:
DateTime.Parse(datestring);
or
DateTime.TryParse(string, IFormatProvider, DateTimeStyles, out DateTime)
Look at the DateTime.Parse method. You can use the DateTimeFormatInfo class as IFormatProvider. There you could specify the format of the date you want to parse.
Im not sure what "date strings like the following" means since seems you forgot to provide a example. But maybe if you try this.
string date = DateTime.Today.ToString("ddd MMM d HH:mm:ss G'M'Tzzz yyyy", CultureInfo.CreateSpecificCulture("en-EN"));
date = date.Remove(date.LastIndexOf(':'), 1);
// Do whatever you want with the date string
// Output looks like Wed Sep 9 00:00:00 GMT+0200 2009
That looks like a simple RFC formatted date, so a straight DateTime.Parse as Ikke said will work and you shouldn't have to provide the format. You can pass a DateTime object as the second argument in the DateTime.TryParse method to see whether it fails or not, as it returns a boolean.