简体   繁体   中英

DateTime value passing incorrectly from javascript to C#

I am using the below code to make call to the controller

DateFrom: moment.utc($(".datefrom").val(), "DD/MM/YYYY").toString()

in the ajax call I had a breakpoint and checked what is being passed and the value was

"Wed Jun 20 2018 00:00:00 GMT+0000"

But when I check it in the C#, this is what is getting passed

在此输入图像描述

Other values are getting passed correctly, but this DateFrom has an issue

I checked both the property names and they are exactly the same.

What am I missing?

Always serialize DateTime values using ISO8601 notation. Most libraries, including momentjs, have built in methods for converting a datetime instance to an ISO8601 string and for parsing them from an ISO8601 back to a datetime instance (no additional call needed for momentjs when parsing, the constructor will handle it without additional input).

Keep in mind this is a separate concern from displaying the value on screen. The display and/or edit value should be localized for the user doing the viewing/entry. The serialized value is the value as it is sent between tiers or devices.

This is because javascript use dates as milliseconds since 1970-01-01 and c# 01/01/1900 so in milliseconds there are a big difference.

I suggest you change your string format to dd/MM/yyyy HH:mm:ss .

The best way is converting your date in javascript to a string that c# can recognize.

var date = new Date();
var day = date.getDate();       // yields date
var month = date.getMonth() + 1;    // yields month (add one as '.getMonth()' is zero indexed)
var year = date.getFullYear();  // yields year
var hour = date.getHours();     // yields hours 
var minute = date.getMinutes(); // yields minutes
var second = date.getSeconds(); // yields seconds
var data= day + "/" + month + "/" + year + " " + hour + ':' + minute + ':' + second;

After that send the "data" to your controller in C#

DateTime date=DateTime.ParseExact(data, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

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