问题
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.
回答1:
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.
回答2:
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);
回答3:
Try DateTime.Parse method to parse your date.
回答4:
This should work:
XmlConvert.ToDateTime(textBox1.Text, "ddd MMM dd HH:mm:ss 'GMT'zzzz yyyy");
来源:https://stackoverflow.com/questions/11618459/troubles-parsing-datetime-from-string