mercu
mercu

Reputation: 131

Convert to correct DateTime

I have questions on this date (from "Jira" REST API Result ->Worklog->Started field) where it returns different result form what I expected.

Questions:

  1. What kind/type of date format is this?
  2. Why is returning different result. String Date:2017-06-20T22:09:00.000-0400 C# DateTime.Parse Result: {6/21/2017 10:09:00 AM}

Can you please provide the correct way to convert this to its correct time?

Upvotes: 1

Views: 603

Answers (2)

Gareth
Gareth

Reputation: 911

Times and GMT offsets often lead to confusion.

Firstly, what does "it's 8:15am here" mean? GMT? London? Somewhere else? Secondly, what does "GMT + 2" mean?

In the first case the honest answer is there is no way to tell without a little more context. In the second case it's more down to people misunderstanding GMT offsets - many people believe that "GMT == London" so "GMT + 2 == London + 2" - of course that's not correct, "GMT == London in winter; BST (GMT + 1) == London in summer". So "GMT + 2" is "GMT + 2", i.e. somewhere like Berlin in the summer or Nicosia in the winter.

For these reasons many situations where time is important use GMT or another timezone but clearly state the offset, e.g. "3:15am, EDT".

To answer your question you have a few options

  • Allow for the timezone in the things you're doing; maybe changing it to GMT to make things easier - you'd then be doing GMT +/- rather than GMT - 4 +/-.
  • Alternatively, you could do something along the same lines as the answer to this question.

Something like this

DateTimeOffset date = new DateTimeOffset(2017, 6, 20, 22, 09, 0, 0, TimeSpan.FromHours(-4));
// 20 June 2017, 22:09, GMT-4

public static DateTimeOffset ParseIso8601(string iso8601String)
{
    return DateTimeOffset.ParseExact(
        iso8601String,
        new string[] { "yyyy-MM-dd'T'HH:mm:ss.FFFK" },
        CultureInfo.InvariantCulture,
        DateTimeStyles.None);
}

Upvotes: 0

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34244

It is an ISO format - the most preferable and inambiguous date format which represents a moment of time in specific time zone.

2017-06-20T22:09:00.000-0400 represents June 20, 2017 22:09 PM in time zone GMT -4.

ISO format is correctly parsed by most languages including C#.

The reason why you get another value in your code is because you are located in GMT +8 and your local time is June 21 10:09 AM when it is June 20 22:09 PM in GMT -4.
It is an absolutely valid and expected behaviour.

Upvotes: 3

Related Questions