Javascript Date to C# Sortable ("s") Format

578 Views Asked by At

I am trying to pass DateTime as string to my Web API service and parsing it to sortable datetime in c#. Please find the code below:

public static DateTime? ToDateTime(this string dateTime)
    {
        if (string.IsNullOrEmpty(dateTime))
        {
            return null;
        }
        return DateTime.ParseExact(dateTime, Constant.DateFormat, CultureInfo.InvariantCulture);
    }

Client side code:

var d = new Date();
var dateTime = JSON.stringify(d); // e.x: "2014-01-01T23:28:56.782Z"

I tried below options as well:

d.toLocaleDateString()); 
d.toLocaleString();
d.toDateString();

Any help is highly appreciated.

1

There are 1 best solutions below

3
On BEST ANSWER

if you insist passing it as a string so you could use momentjs

moment().format('MMMM Do YYYY, h:mm:ss a');

and than you could parse it with format on the server side

You did not provide you web api code but another approach would be to change the serializer for Datetime on the server side

// class to be serialized
public class MyClass
{
    [JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
    public DateTime? DateTime1;
    public DateTime? DateTime2;
}