2

i am trying to convert this string i get from the customer to a datetime, to store it in my db.

i tried several approches but nothing seems to work. i need the offset in UTC time so i guess i need to do something with zz.

This is working:

string   test = "2008-06-11T16:11:20.0904778Z";
DateTime publishingTimeStamp = DateTime.ParseExact(test, "o", CultureInfo.InvariantCulture,
             DateTimeStyles.None);

But the string by the customer is slightly different, so i tried this one:

string   test = "2017-01-01T12:00:33:123456Z+02"; 
DateTime publishingTimeStamp = DateTime.ParseExact(test, "yyyy-MM-dd'T'HH:mm:ss:ffffffzz", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None);

Unfortunaly it is not working. How can i convert the exact string "2016-01-01T10:00:55:123456Z+02"? Is it even possible because it uses ":" in front of ffffff

Thank you

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
Monika_Aydt
  • 111
  • 1
  • 1
  • 5
  • 1
    *"...it is not working"* How? What result do you get and what result do you expect? Do you get an error? If yes, which one? – Heinzi Apr 12 '16 at 12:00
  • Why `ParseExact`? You can use simple `DateTime.Parse(test, out dt)`. With ISO string it does not need culture, format, etc. – i486 Apr 12 '16 at 12:04
  • No, that was [my initial answer](http://stackoverflow.com/a/36572742/993547) but the format deviates from that format too much @i486 – Patrick Hofman Apr 12 '16 at 12:09
  • 1
    You use `Z+02` at the end. Normally the UTC offset is instead of the `Z`, as Z means UTC or +00. Are you sure there is a `Z` before the offset? – wimh Apr 12 '16 at 12:09
  • Indeed, that date format is invalid @Wimmel That is why I deleted my answer. The customer of OP should use standard formatting for dates. – Patrick Hofman Apr 12 '16 at 12:09

1 Answers1

6

Looks like you forget to escape Z as a string literal delimiter in your format as 'Z'.

string test = "2017-01-01T12:00:33:123456Z+02";
DateTime publishingTimeStamp = DateTime.ParseExact(test, 
                                    "yyyy-MM-dd'T'HH:mm:ss:ffffff'Z'zz", 
                                    CultureInfo.InvariantCulture, DateTimeStyles.None);
Console.WriteLine(publishingTimeStamp); // 01.01.2017 12:00:33

But since your string has UTC Offset value, I would parse it to DateTimeOffset instead.

string test = "2017-01-01T12:00:33:123456Z+02";
DateTimeOffset publishingTimeStamp = DateTimeOffset.ParseExact(test, 
                                    "yyyy-MM-dd'T'HH:mm:ss:ffffff'Z'zz", 
                                     CultureInfo.InvariantCulture, 
                                     DateTimeStyles.None);

Now you have a DateTimeOffset as {01.01.2017 12:00:33 +02:00}

enter image description here

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364