I am getting timestamp string in the following format -
2015-02-01T12:11:06Z
I need to convert it into DateTime object. I tried the following code for this -
timestamp = DateTime.ParseExact(attr.Value,"yyyy-MM-ddThh:mm:ss",null);
But it's throwing Exception.
System.FormatException: String was not recognized as a valid DateTime.
at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)
I know that my format is wrong. Any way to make it work?
Update
J. Steen's method worked for me and he was the first one to comment, but Soner Gönül provided much better explanation and a better way, so I am accepting Soner Gönül's answer as mentioned here and as J. Steen agreed with this. Thanks to both of you. I am upvoting all the correct answers anyways. :-)
You forget the Z
part at the end and change hh
to HH
;
string s = "2015-02-01T12:11:06Z";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt); // 01/02/2015 14:11:06
}
Since there is no custom date and time format as Z
, parsing methods see it as a character literal. But in such a case, your hour part will be different with OffSet
since this operation creates your DateTimeKind
as Local
. Since my current offset is +02:00
right now, it will generate 14:11:06
, not 12:11:06
string s = "2015-02-01T12:11:06";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt); // 01/02/2015 12:11:06
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加