Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get consistent date time value with Newtonsoft.JSON JObject

Tags:

c#

json.net

I have a ASP.Net Core service that uses Newtonsoft.Json library for working with JSON data. The sample JSON input has a string that holds a date value in ISO8601 format. However I am observing different date time value being returned for an equivalent date. Here is the sample code -

    var jsonString = @"{
        ""data"": {
            ""name"": ""John Doe"",
            ""dateOfBirth"": ""1990-05-25T15:54:49.119+00:00""
        }
    }";

    var jsonObj = JObject.Parse(jsonString);
    var person = jsonObj.ToObject<Person>();

    DateTime dateOfBirth = DateTime.Parse(person.Data.DateOfBirth);
    if (dateOfBirth.Kind != DateTimeKind.Utc)
    {
        dateOfBirth = dateOfBirth.ToUniversalTime();
    }
    Console.WriteLine("Date of birth is " + dateOfBirth.ToString("o"));

The Person class is like this -

class Person
{
    public PersonalData Data;
}

class PersonalData
{
    public  string Name { get; set; }
    public string DateOfBirth { get; set; }
}

If I provide ""dateOfBirth"": ""1990-05-25T15:54:49.119+00:00"", the output is -

Date of birth is 1990-05-25T15:54:49.0000000Z

If I provide ""dateOfBirth"": ""1990-05-25T15:54:49.119Z"", the output is -

Date of birth is 1990-05-25T10:24:49.0000000Z

As it can be seen, the output is different where as it should have been same. The callers can set any date time string in ISO8601 format.

Is there any way where this can be handled consistently?

like image 530
tyrion Avatar asked Oct 28 '25 05:10

tyrion


1 Answers

This is because DateTime.Parse() takes into account the system time zone (of the computer you run this code)

The solution is here

   var jsonString = @"{
        ""data"": {
            ""name"": ""John Doe"",
            ""dateOfBirth"": ""1990-05-25T15:54:49.119+00:00""
        }
    }";
var jsonObj = JObject.Parse(jsonString);
var person = jsonObj.ToObject<Person>();

var dateTimeOffset = DateTimeOffset.Parse(person.Data.DateOfBirth, CultureInfo.InvariantCulture);
DateTime dateOfBirth = dateTimeOffset.UtcDateTime;
Console.WriteLine("Date of birth is " + dateOfBirth.ToString("o"));
like image 62
Sunil Purushothaman Avatar answered Oct 30 '25 22:10

Sunil Purushothaman