Shirish
Shirish

Reputation: 9

Displaying correct datetime value

I'm in the US timezone. I'm trying to parse following dates using C#. What should be the correct value that should be displayed to them user for the following input dates that I'm receiving from another system ?

1.2017-10-04T16:24:55.000-04:00 

2.2017-10-04T13:14:35.000+04:00

Thanks.

Upvotes: 0

Views: 67

Answers (2)

grek40
grek40

Reputation: 13448

First of all, do not use DateTime, but use DateTimeOffset (or some NodaTime type, as @DiskJunky mentioned). This allows you to parse / store each value with the given time offset.

Your provided texts should work well with default parsing:

string test1 = "2017-10-04T16:24:55.000-04:00";
string test2 = "2017-10-04T13:14:35.000+04:00";

DateTimeOffset dateTime;
if (DateTimeOffset.TryParse(test1, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
    Console.WriteLine("Date 1: " + dateTime);
}
if (DateTimeOffset.TryParse(test2, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
    Console.WriteLine("Date 2: " + dateTime);
}

When the time values are parsed as DateTimeOffset you can convert and display them any way you want... for example, get your US adjusted time with dateTime.ToLocalTime() or get an easier international exchangeable value with dateTime.ToUniversalTime().

Upvotes: 1

DiskJunky
DiskJunky

Reputation: 4971

The recommended way of this accurately is to use a library like NodaTime if you're going to be displaying dates to a user and need to account for time zones. Apart from UTC differences there are also regional DSTs to account for and it's a general nightmare to work with accurately without using a 3rd party library.

Upvotes: 0

Related Questions