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 Overflow
🌐
GitHub
github.com › HangfireIO › Hangfire › issues › 2183
Could not convert string to DateTime: 27.03.2023 07:30:00. Path 'CreatedAt', line 1, position 100. · Issue #2183 · HangfireIO/Hangfire
November 26, 2022 - Newtonsoft.Json.JsonReaderException Could not convert string to DateTime: 27.03.2023 07:30:00. Path 'CreatedAt', line 1, position 100. Newtonsoft.Json.JsonReaderException: Could not convert string to DateTime: 27.03.2023 07:30:00. Path 'CreatedAt', line 1, position 100.
Author   steinbachio
🌐
UiPath Community
forum.uipath.com › help › studio
Convert string to DateTime not working - Studio - UiPath Community Forum
February 6, 2022 - Hello to all, I have been reading all I could find in this forum about converting strings into datetime, but none of the threads answer this question. I am reading a excel file and there is a column with date. This date, tho, can rather be a string or a date, and to check if is a date I use IsDate. However, when it is not ...
🌐
Alteryx Community
community.alteryx.com › t5 › Alteryx-Designer-Desktop-Discussions › Cannot-convert-string-to-datetime-format › td-p › 934595
Cannot convert string to datetime format - Alteryx Community
May 5, 2022 - My guess is that somewhere in your records (for example the record # Alteryx flagged up), there are dates not fitting the input format and therefore not allowing the formula to run. Could actually test this (I believe), by seeing if it still runs - but gives you some nulls - with the following: IF DateTimeParse([INVOICE_DATE],"%Y-%m-%d") != DateTimeFormat([INVOICE_DATE],"%Y-%m-%d") then Null() else DateTimeFormat([INVOICE_DATE],"%Y-%m-%d") endif
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 480339 › error-converting-string-to-datetime-on-a-system-co
Error Converting String to DateTime on a System Console - Microsoft Q&A
string datacadastro1 = Console.ReadLine(); // the datacadastro1 needs to meet the "dd/MM/yyyy HH:mm" format. such as 19/07/2021 14:30 DateTime datacadastro = Convert.ToDateTime(datacadastro1, System.Globalization.CultureInfo.GetCultureInfo("pt-BR").DateTimeFormat); ... If the response is helpful, please click "Accept Answer" and upvote it. Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
🌐
Syncfusion
syncfusion.com › forums › 155026 › could-not-convert-string-to-datetime
Could not convert string to DateTime | Blazor Forums | Syncfusion®
December 26, 2019 - We suspect that you have defined the ResourceDate property as DateTime in your model class. To resolve the issue, kindly define the type of ResourceDate as DateTime? (nullable datetime) in your model class (ResourceForGridDTO).
🌐
OutSystems
outsystems.com › forums › discussion › 97684 › could-not-convert-string-to-datetime
Could not convert string to DateTime | OutSystems
I am calling an API thought that I am getting date format like this : 20240618153915.341Z. when I am trying to parse in attribute of datetime its giving error "Could not convert string to DateTime" · HI Could you do it with JavaScript and format the date hen use the 'Convert Text to Date' ...
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 487709 › could-not-convert-string-to-datetime
.net - Could not convert string to DateTime [SOLVED] | DaniWeb
The error is raised before your SQL filter is built: the binder/deserializer cannot parse the user input "18/11/2014" into a DateTime because the current culture likely expects MM/dd/yyyy (18 is not a valid month). Either send an ISO 8601 date (recommended) or parse the input explicitly with the correct culture. JSON parsers and most frameworks handle ISO 8601 like "2014-11-18" or "2014-11-18T00:00:00" reliably; see Dates in JSON (Newtonsoft) and .NET DateTime parsing. Also, avoid string-concatenating "23:59:59".
Find elsewhere
Top answer
1 of 2
1

You 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

2 of 2
0

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>

🌐
ASP.NET Zero
support.aspnetzero.com › QA › Questions › 12382 › Could-not-convert-string-to-DateTime-17022025-Path-'dateFrom'-line-1-position-502
Could not convert string to DateTime: 17/02/2025. Path 'dateFrom', line 1, position 502. #12382 | Support Center | ASP.NET Zero Support
Here, before sending to AppService, can you print the workOrderItem object to the console screen in both languages? In this way, we will see which format AppService is sending. Also, if you want to update to the latest version, "datetimepicker" is not used, "daterangepicker" is used to get the date information from the input.
Top answer
1 of 2
1

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.

2 of 2
1

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; }
}
🌐
OutSystems
outsystems.com › forums › discussion › 95422 › text-to-datetime-conversion
Text to DateTime conversion | OutSystems
I'm trying to convert Text (String) to DateTime From an API But it throws me an error.I tried TextToDateTime() but it doesn't help "OS-BERT-60600 - Error executing GetAllAttributes Failed to deserialize JSON to Response: Failed to parse response of the method 'GetAllAttributes' of the 'Analytics' ...
🌐
UiPath Community
forum.uipath.com › help › studio
Convert String to DateTime throws Error - Studio - UiPath Community Forum
October 23, 2021 - Hi I am trying to convert a String into DateTime Variable, but the following Error occoured: “The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar” Here is what i did: (I replaced my Stringvalue with DateTime.now.toString, because it throws the same Error) Log Message DateTime.now.toString Assingn Test (DateTime) = DateTime.ParseExact(DateTime.now.ToString,“dd/MM/yyyy HH:mm:ss”,system.globalization.CultureInfo.InvariantCulture) Output...
🌐
Reddit
reddit.com › r/bigquery › unable to convert strings to datetime objects
r/bigquery on Reddit: Unable to convert strings to datetime objects
December 27, 2018 -

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.

🌐
GitHub
github.com › pandas-dev › pandas › issues › 14561
Invalid datetime string conversion giving SystemError with Python 3.6.0b3 · Issue #14561 · pandas-dev/pandas
In [56]: pd.Timestamp('next') ... series of "During handling of the above exception, another exception occurred:" ... /home/joris/scipy/pandas/pandas/tslib.pyx in pandas.tslib.convert_str_to_tsobject (pandas/tslib.c:27281)() 1537 ts, dayfirst=dayfirst, yearfirst=yearfirst) 1538 except Exception: -> 1539 raise ValueError("could not convert string to Timestamp") 1540 1541 return convert_to_tsobject(ts, tz, unit, dayfirst, yearfirst) ValueError: could not convert string to Timestamp ·
Top answer
1 of 2
5

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

2 of 2
1

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.

🌐
KNIME Community
forum.knime.com › knime analytics platform
Convert string to datetime - KNIME Analytics Platform - KNIME Community Forum
August 29, 2023 - Hello, I want to convert a column from string to datetime but in my column some rows got this “'24/08/2023”, i can’t convert it. Error message ERROR String to Date&Time 5:181 Execute failed: Failed to parse date in row ‘Row0’: Text ‘24/08/2023’ could not be parsed at index 0