DateTime conversion from UI

Asked by At

I have a form where the user selects the Date from the UI .

I am getting the following value from UI

var uiDate = "2019-05-03T00:00:00.000Z".

I need to convert this to DateTime for further processing .

var dt = Convert.ToDateTime(uiDate);

The value of dt is "5/2/2019 8:00:00PM" .

As we can see I am always getting one day back after DateTime conversion from the date selected from UI. I was expecting "5/3/2019". I am not able to figure out why is this happening after DateTime conversion?

1 Answers

Jon Skeet On Best Solutions

Convert.ToDateTime is implicitly converting the value to local time. If you use DateTime.ParseExact, you can specify appropriate conversion options:

using System;
using System.Globalization;

class Program
    static void Main()
        string text = "2019-05-03T00:00:00.000Z";
        DateTime parsed = DateTime.ParseExact(
            text, // The value to parse
            // The pattern to use for parsing
            // Use the invariant culture for parsing
            // Assume it's already in UTC, and keep it that way
            DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);

        Console.WriteLine(parsed);  // 03/05/2019 00:00:00 (on my machine; format will vary)
        Console.WriteLine(parsed.Kind); // Utc