Try specifying the DateTime format specifically using an IsoDateTimeConverter, and pass it into the JsonConvert.DeserializeObject<>() method.
...
var json = Request.RequestContext.HttpContext.Request.Params["EoiDraftModel"];
var format = "dd/MM/yyyy"; // your datetime format
var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = format };
var ld = JsonConvert.DeserializeObject<EoiDraftViewModel>(json, dateTimeConverter);
...
Answer from IronGeek on Stack OverflowYou could use the moment.js library.
Then simply:
var stringDate = '01-01-1970 00:03:44';
var momentDateObj = moment(stringDate);
Checkout their api also, helps with formatting, adding, subtracting (days, months, years, other moment objects).
Ferdo
For this format (assuming datepart has the format dd-mm-yyyy) in plain javascript use dateString2Date.
Added an ES6 utility method to parse a date string using a format string parameter (format) to inform the method about the position of date/month/year in the input string.
var result = document.querySelector('#result');
result.textContent =
`*Fixed\ndateString2Date('01-01-2016 00:03:44'):\n => ${
dateString2Date('01-01-2016 00:03:44')}`;
result.textContent +=
`\n\n*With formatting\ntryParseDateFromString('01-01-2016 00:03:44', 'dmy'):\n => ${
tryParseDateFromString('01-01-2016 00:03:44', "dmy").toUTCString()}`;
result.textContent +=
`\n\nWith formatting\ntryParseDateFromString('03/01/2016', 'mdy'):\n => ${
tryParseDateFromString('03/01/1943', "mdy").toUTCString()}`;
// fixed format dd-mm-yyyy
function dateString2Date(dateString) {
var dt = dateString.split(/\-|\s/);
return new Date(dt.slice(0,3).reverse().join('-') + ' ' + dt[3]);
}
// multiple formats (e.g. yyyy/mm/dd or mm-dd-yyyy etc.)
function tryParseDateFromString(dateStringCandidateValue, format = "ymd") {
if (!dateStringCandidateValue) { return null; }
let mapFormat = format
.split("")
.reduce(function (a, b, i) { a[b] = i; return a;}, {});
const dateStr2Array = dateStringCandidateValue.split(/[ :\-\/]/g);
const datePart = dateStr2Array.slice(0, 3);
let datePartFormatted = [
+datePart[mapFormat.y],
+datePart[mapFormat.m]-1,
+datePart[mapFormat.d] ];
if (dateStr2Array.length > 3) {
dateStr2Array.slice(3).forEach(t => datePartFormatted.push(+t));
}
// test date validity according to given [format]
const dateTrial = new Date(Date.UTC.apply(null, datePartFormatted));
return dateTrial && dateTrial.getFullYear() === datePartFormatted[0] &&
dateTrial.getMonth() === datePartFormatted[1] &&
dateTrial.getDate() === datePartFormatted[2]
? dateTrial :
null;
}
<pre id="result"></pre>
Supposing the Date value is the number of milliseconds since the start of epoch, you could do something similar to this:
public class MyClass
{
public string Name { get; set; }
public int qty { get; set; }
[JsonProperty("Date")]
public long DateAsMilliseconds { get; set; }
[JsonIgnore]
public DateTime Date => TimeUtils.UnixMillisecondsToDateTime(DateAsMilliseconds);
}
public class TimeUtils
{
public static DateTime UnixMillisecondsToDateTime(double unixTimeStamp)
{
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dateTime = dateTime.AddMilliseconds(unixTimeStamp).ToLocalTime();
return dateTime;
}
}
Update: as suggested in the comments a far better idea would be to use the standard date format ISO8601.
The standard date format in JSON is ISO8601, ie 2021-09-09T10:52:01+00:00 or 2021-09-09T10:52:01Z. JSON.NET never parsed raw numbers as dates. As the docs explain:
The default format used by Json.NET is the ISO 8601 standard: "2012-03-19T07:22Z".
Prior to Json.NET 4.5 dates were written using the Microsoft format: "/Date(1198908717056)/". If you want to use this format, or you want to maintain compatibility with Microsoft JSON serializers or older versions of Json.NET, then change the DateFormatHandling setting to MicrosoftDateFormat.
The only way "1631149200826" can be converted to a DateTime is through a custom type converter.
The correct solution would be to switch to the standard date format.
If you want to keep using JSON.NET, you'll have to add the custom type converter that handled "1631149200826".
It's possible to create a custom DateTime converter for System.Text.Json as well. It's used in a similar way as JSON.NET custom converters, either through serializer options or though JSON attibutes.
In this case, the converter could be:
public class DateTimeMilliJsonConverter : JsonConverter<DateTime>
{
public override DateTime Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options)
{
long millis=long.Parse(reader.GetString());
return DateTime.UnixEpoch.AddMilliseconds(millis);
}
public override void Write(
Utf8JsonWriter writer,
DateTime dateTimeValue,
JsonSerializerOptions options)
{
long millis=(long)dateTimeValue.Subtract(DateTime.UnixEpoch).TotalMilliseconds;
writer.WriteStringValue(millis.ToString());
}
}
The converter can be applied to a property through the JsonConverter attribute
public class MyClass
{
public string Name { get; set; }
public int qty { get; set; }
[JsonConverter(typeof(DateTimeOffsetJsonConverter))]
public DateTime Date { get; set; }
}
Hi,
I was trying to convert some strings to datetime objects. After these strings are converted to datetime objects, I intend to extract the date from these datetime objects based on my timezone. However, when I cast the string to a datetime object, I am getting an error.
Code:
cast(json_extract_scalar(data, "$.end_date") as datetime) as end_date_datetime
Error:
Invalid datetime string "2020-12-31T18:29:59Z"
Please let me know what I'm doing wrong here. I've tried searching stackoverflow but found nothing there.
Edit : I'm sorry to not mention this earlier but, the output from json_extract_scalar(data, "$.end_date") is in string format.
I'll answer your question if you tell me which generator you used to come up with that user name.
Check out parse_datetime, you have to specify the format of your string so it knows what values you are converting from string to datetime. You specify the format by using ‘%Y-%M-%d.... etc” you can’t just straight cast any string to a datetime you need to reference the format of your string so it knows how to parse it.
Edit: check this out, I just woke up otherwise I would write it for you
Looks like your error is not in the line started with var insertdata = new ClientIndividualTable but some lines before that.
Your error is likely raising in a line similar to this one.
MyJsonClass item = JsonConvert.DeserializeObject<MyJsonClass>(fileText);
You must create a DateTime converter so Newtonsoft does know how to handle the custom format used. After that, you must decorate the class used to add a attribute to the DateTime property.
Sample JSON File:
{
"COID" : "myCompanyId",
"CLIENTID" : "myClientId",
"BIRTHDAY" : "20-09-1982 12:00:00",
}
The class that matches the JSON structure:
public class MyJsonClass
{
public string COID { get; set; }
public string CLIENTID { get; set; }
[JsonConverter(typeof(CustomDateTimeConverter))]
public DateTime? BIRTHDAY { get; set; }
}
And the JsonConverter would be similar to this.
public class CustomDateTimeConverter : DateTimeConverterBase
{
private const string Format = "dd-MM-yyyy HH:mm:ss";
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((DateTime)value).ToString(Format));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null)
{
return null;
}
var s = reader.Value.ToString();
DateTime result;
if (DateTime.TryParseExact(s, Format, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
{
return result;
}
return null;
}
}
Note: I have based my answer in this blog post
You could use DateTime.ParseExact like this
DateTime.ParseExact("20-09-1982 12:00:00", "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
ParseExact allows you to specify exactly the format you are storing no matter how many extra characters may be present.