0

So I got this datetime-string which I get from an external API, "2014-08-28T11:00:00:000-0400".

But I am unable to parse it into a normal DateTime object in C#, I know that last part of the string has something to do with timezone offsets or something, but I am at a loss as to what to do in order for it to parse.

What I've tried so far:

DateTime.Parse("2019-11-13T05:20:14:311-0700")
DateTime.Parse("2019-11-13T05:20:14:311-0700", new System.Globalization.CultureInfo("en-GB"))
DateTime.Parse("2019-11-13T05:20:14:311-0700", new System.Globalization.CultureInfo("en-US"))
DateTimeOffset.Parse("2019-11-13T05:20:14:311-0700")

A whole other bunch of stuff where I've passed in various format strings like "yyyy-MM-dd:HH:mm:ss" but that doesn't do any good either

Please, if someone out there can help me, you'll get a virtual cookie!

sayah imad
  • 1,507
  • 3
  • 16
  • 24
mpma
  • 35
  • 4
  • 3
    Please show us what you have done so far. – Vroomfondel Nov 13 '19 at 13:38
  • 1
    Does this answer your question? [C# string to DateTime with timezone](https://stackoverflow.com/questions/10293362/c-sharp-string-to-datetime-with-timezone) – Mahesh Waghmare Nov 13 '19 at 13:39
  • `DateTime.ParseExact` - https://stackoverflow.com/questions/8401605 - https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parseexact – Rand Random Nov 13 '19 at 13:39
  • I've updated the post with what i've tried so far – mpma Nov 13 '19 at 13:43
  • @MaheshWaghmare that doesn't do me any good either, since my datetime string does't look like: 2012-04-20T10:10:00+0200 notice the extra "000" that I have before "0400" – mpma Nov 13 '19 at 13:45
  • As per @Jamiec comment. I have checked and it is working. :- `DateTimeOffset result = DateTimeOffset.ParseExact("2014-08-28T11:00:00:000-0400", "yyyy-MM-dd'T'HH:mm:ss:fffzzz", CultureInfo.InvariantCulture);` – Mahesh Waghmare Nov 13 '19 at 13:51

1 Answers1

2

The format string you want to use is either

yyyy-MM-dd'T'HH:mm:ss:fffzzz

or

yyyy-MM-dd'T'HH:mm:ss:fffK

More information for zzz can be found here or for K here

You can use the above format string with either DateTime.ParseExact or DateTimeOffset.ParseExact depending on what you're trying to achieve.

Live example: https://rextester.com/DTNT63275

Jamiec
  • 133,658
  • 13
  • 134
  • 193