Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Data comes from a JSON file. The data seems to be "french" as the properties are in french.

ParseAndPrint("2023-03-30T19:15:22.000Z");
ParseAndPrint("2023-03-30T13:29:01.000Z");
ParseAndPrint("2023-03-30T01:32:55.000Z");

void ParseAndPrint(string s)
{
    var c = DateTime.Parse(s, CultureInfo.InvariantCulture);
    Console.WriteLine($"c : {c.ToShortDateString()}");
}


c : 2023-03-30
c : 2023-03-30
c : 2023-03-29


Any Thoughts ?

What I have tried:

I tried with and without CultureInfo.InvariantCulture.
I tried with the "fr-FR" culture (I think my data is using it ... )
Posted
Updated 15-Apr-23 14:01pm
Comments
[no name] 13-Apr-23 11:56am    
If the time is (somewhere) before "noon", it appears you get the day before ("rounding" in the "short date" apparently). Reference the year, month and day explicitly in this case. (Display the DateTime as well to confirm).
Richard MacCutchan 13-Apr-23 11:56am    
Those are Zulu (aka UTC) times. However when you display them your system adjusts them to your local timezone.

[edit]
2023-03-30T01:32:55.000Z UTC is 2023-03-29T20:32:55.000 in Quebec (or 21:32 if on DST).
[/edit]

Your system is using something - buts looks like ISO date format, not French.
Try parsing it use ParseExact instead:
C#
var c = DateTime.ParseExact(s, "yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture);
 
Share this answer
 
You can just use ToUnvisersalTime() like this

var c = DateTime.Parse(s).ToUniversalTime();
 
Share this answer
 
This ISO date format is official date format in Canada or at least in some jurisdictions. Try with Canada(french) culture. I never tried DateTime with Canada(English) Culture.

A word of caution. In Canadian real-life you may face US, Great-Britain or ISO date format.
 
Share this answer
 
Ah, everyone missed the important bit, this is being read from JSON. You need to deserialize to the correct object, the DateTimeOffset Struct (System) | Microsoft Learn[^].

Here is an example:
C#
using Newtonsoft.Json;

string rawJson = File.ReadAllText("sample_date.json");

Result result = JsonConvert.DeserializeObject<Result>(rawJson);

Console.WriteLine($"Date: {result.Date}");
Console.ReadKey();

public class Result
{

    [JsonProperty("date")]
    public DateTimeOffset Date { get; set; }
}

and here is the output (en-AU):
Date: 30/03/2023 1:32:55 AM +00:00

and here is the sample JSON used:
JavaScript
{
  "date": "2023-03-30T01:32:55.000Z"
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900