简体   繁体   中英

Javascript Date to C# Sortable (“s”) Format

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM