将日期时间从javascript传递给c#(控制器)

Tij*_*ija 60 c# jquery json asp.net-mvc-3

你如何使用jquery和mvc3将日期时间(我需要它到第二个)传递给c#.这就是我所拥有的

var date = new Date();    
$.ajax(
   {
       type: "POST",
       url: "/Group/Refresh",
       contentType: "application/json; charset=utf-8",
       data: "{ 'MyDate': " + date.toUTCString() + " }",
       success: function (result) {
           //do something
       },
       error: function (req, status, error) {
           //error                        
       }
   });
Run Code Online (Sandbox Code Playgroud)

我不知道日期应该是什么格式,让C#理解它.

rno*_*nko 77

尝试使用toISOString().它以ISO8601格式返回字符串.

GET方法

JavaScript的

$.get('/example/doGet?date=' + new Date().toISOString(), function (result) {
    console.log(result);
});
Run Code Online (Sandbox Code Playgroud)

C#

[HttpGet]
public JsonResult DoGet(DateTime date)
{
    return Json(date.ToString(), JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)

POST方法

JavaScript的

$.post('/example/do', { date: date.toISOString() }, function (result) {
    console.log(result);
});
Run Code Online (Sandbox Code Playgroud)

C#

[HttpPost]
public JsonResult Do(DateTime date)
{
     return Json(date.ToString());
}
Run Code Online (Sandbox Code Playgroud)

  • toISOString()的作用不在这里提到。我将JS日期从2018年2月4日转换为utc日期,将其转换为2018年2月3日2300Z,然后在服务器端:03/02/2018 23:00:00所以我必须这样做:myDate.ToLocalTime()(假设当前的文化是DE),那么我得到了04.02.2018。 (2认同)

Dar*_*rov 29

以下格式应该有效:

$.ajax({
    type: "POST",
    url: "@Url.Action("refresh", "group")",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ 
        myDate: '2011-04-02 17:15:45'
    }),
    success: function (result) {
        //do something
    },
    error: function (req, status, error) {
        //error                        
    }
});
Run Code Online (Sandbox Code Playgroud)

  • @amonteiro,当然,你总是可以在发送前通用时间转换数据,这样在服务器上就可以转换回服务器本地时间. (2认同)

Kam*_*ran 7

toJSON()javascript中有一个方法返回Date对象的字符串表示。toJSON()是 IE8+,toISOString()是 IE9+。两种结果都是YYYY-MM-DDTHH:mm:ss.sssZ格式。

var date = new Date();    
    $.ajax(
       {
           type: "POST",
           url: "/Group/Refresh",
           contentType: "application/json; charset=utf-8",
           data: "{ 'MyDate': " + date.toJSON() + " }",
           success: function (result) {
               //do something
           },
           error: function (req, status, error) {
               //error                        
           }
       });
Run Code Online (Sandbox Code Playgroud)