Reputation: 1721
I found many questions about parsing datetime from various formats, but not able to find the solution to my problem of converting datetime string with milliseconds and timezone both.
My input is like
20110713014230.685+0000
And format of this is like:
yyyyMMddHHmmss.fff+zzzz
I tried DateTime.ParseExact and DateTimeOffset.ParseExact with/without +
and .
but nothing worked.
Found similar question Here but it's not working for me.
I get the exception
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Upvotes: 3
Views: 4728
Reputation: 61
With dateTimeString = 20110713014230.685+0000 the following code should get you what you want:
if (!DateTimeOffset.TryParseExact(dateTimeString,
"yyyyMMddHHmmss.fffzzz",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out var dateTimeWithOffset)){}
Here's the intermediate output of the dateTimeWithOffset var:
{7/13/2011 1:42:30 AM +00:00}
ClockDateTime: {7/13/2011 1:42:30 AM}
Date: {7/13/2011 12:00:00 AM}
DateTime: {7/13/2011 1:42:30 AM}
Day: 13
DayOfWeek: Wednesday
DayOfYear: 194
Hour: 1
LocalDateTime: {7/12/2011 9:42:30 PM}
Millisecond: 685
Minute: 42
Month: 7
Offset: {00:00:00}
Second: 30
Ticks: 634461181506850000
TimeOfDay: {01:42:30.6850000}
UtcDateTime: {7/13/2011 1:42:30 AM}
UtcTicks: 634461181506850000
Year: 2011
_dateTime: {7/13/2011 1:42:30 AM}
_offsetMinutes: 0
Upvotes: 0
Reputation: 1374
DateTime date;
var dateString = "20110713014230.685+0000";
dateString = dateString.Substring(0, 21) + ':' + dateString.Substring(21, 2);
DateTime.TryParseExact(dateString, "yyyyMMddHHmmss.fffzzz", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
Upvotes: 0
Reputation: 4823
Change the format to yyyyMMddHHmmss.fffzzzzz
, acording the documentation, the "zzz" custom format specifier represents the signed offset of the local operating system's time zone.
Upvotes: 5