DateTime - Replace argument field with json file data

Hello,

I have a script to calculate a number of Days between one date and Today:

DateTime dt2 = new DateTime(2024,07,24);
int ireturn = (int)dt2.Subtract(DateTime.Now).TotalDays;

It’s work fine.
But now I need to use the argument (2024,07,24) from a json file instead of directly into the script.

(My data in the field of the json file looks like {“Date”: “2024,07,24”)}
So I can use the link: myJsonFile.Date

Is it possible ?

Many Thanks

There are two steps here:

  1. parse the JSON into a class… to this end, be sure to leverage sites like:

https://jsonlint.com
https://json2csharp.com
https://csharp2json.io

  1. Once you have a string “2024,07,24” you need to chop it up according to those delimiters, whatever they are (culture-invariant or otherwise). Look up regular expressions for this, as well as likely int.TryParse() to get each string segment converted into an integer.

If you can reshape the JSON string, you can use methods in System.DateTime() to serialize/deserialize time / date values in a consistent fashion, but they will be formatted differently, most likely.

He he, thank you,

It’s look a bit complicated for me but I have to study

Ok,
I have used the json2csharp to convert and I have this:

(i have simplify the field date for testing, now it’s “Date”:“2024”)

public class Root
{

public string Date { get; set; }

}

Ok, but what I do with that ? :slight_smile:

You definitely want to get familiar with converting your data from string to numeric (integer in this case).

As I wrote above yesterday,

The JSON specification does not specify a format for exchanging dates which is why there are so many different ways to do it. JSON does not know anything about dates. What .NET does is a non-standard hack/extension. The problem with JSON date and really JavaScript in general – is that there’s no equivalent literal representation for dates. In JavaScript following Date constructor straight away converts the milliseconds since 1970 to Date as follows:

var jsonDate = new Date(1297246301973);

Then let’s convert it to js format:

var date = new Date(parseInt(jsonDate.substr(6)));

The substr() function takes out the /Date( part, and the parseInt() function gets the integer and ignores the )/ at the end. The resulting number is passed into the Date constructor .

For ISO-8601 formatted JSON dates, just pass the string into the Date constructor:

var date = new Date(jsonDate);