1

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?

user1400915
  • 1,933
  • 6
  • 29
  • 55

1 Answers1

1

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
            "yyyy-MM-dd'T'HH:mm:ss.FFF'Z'",
            // Use the invariant culture for parsing
            CultureInfo.InvariantCulture,
            // 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
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • could you please help me with similar question? https://stackoverflow.com/questions/63037209/datetime-conversion-from-mongodb-string-to-sql – newdeveloper Jul 22 '20 at 14:57
  • @newdeveloper: That's not really a similar question - this is entirely about text conversions in .NET; that's about SQL. I see you've also pinged two other people in the same way, admittedly on more relevant questions. Please don't do this. Just let the question get attention organically. (Imagine if everyone who asked a new question thought one of my 35,000 answers was related to it, and decided to notify me...) – Jon Skeet Jul 22 '20 at 15:14
  • sorry about that. atleast got your attention :) yes.. I will be careful with that in future. – newdeveloper Jul 22 '20 at 15:16