ASP.NET Parse DateTime 结果从 ajax 调用到 javascript 日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27314663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:19:16  来源:igfitidea点击:

ASP.NET Parse DateTime result from ajax call to javascript date

javascriptc#jqueryasp.netajax

提问by Mivaweb

Introduction:

介绍:

I have a WebMethodon my ASP.NET page which returns a Personobject. One of the fields is Birthdaywhich is a DateTimeproperty.

WebMethod在我的 ASP.NET 页面上有一个返回一个Person对象。其中一个字段是Birthday哪个是DateTime属性。

WebMethod

网络方法

[WebMethod]
public static Person GetPerson()
{
     Person p = new Person() {
         Id = 1,
         Name = "Test",
         Birthday = new DateTime(1988, 9, 13)
     };

     return p;
}

If I make the call using $.ajax()I get the response of the server with the Personobject.

如果我使用调用$.ajax()我得到服务器的响应与Person对象。

Ajax call

Ajax 调用

// Class instance
var Ajaxcalls = function () {

}

_$.extend(Ajaxcalls, {
    GetPerson: function (label) {
        var self = label instanceof _$ ? label : $(label);

        _$.ajax({
            url: 'Default.aspx/GetPerson',
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                console.log(JSON.stringify(data.d));
                self.html(new Date(Date.parse(data.d.Birthday)));
            }
        });
    }
});

Result:

结果:

{"__type":"AjaxTest.Classes.Person","Id":1,"Name":"Test","Birthday":"/Date(590104800000)/"}

Problem

问题

How do I parse the Birthday[/Date(590104800000)/] to a javascript/jQuery date? I tried new Date(Date.parse(data.d.Birthday))but it gives me an Invalid date.

如何将Birthday[/Date(590104800000)/]解析为 javascript/jQuery 日期?我试过了,new Date(Date.parse(data.d.Birthday))但它给了我一个Invalid date.

回答by Arunprasanth K V

Use convertToJavaScriptDate()function that does this for you:

使用convertToJavaScriptDate()为您执行此操作的函数:

function convertToJavaScriptDate(value) {
  var pattern = /Date\(([^)]+)\)/;
  var results = pattern.exec(value);
  var dt = new Date(parseFloat(results[1]));
  return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}

The convertToJavaScriptDate()function accepts a value in \/Date(ticks)\/format and returns a date string in MM/dd/yyyyformat.
Inside, the convertToJavaScriptDate()function uses a regular expression that represents a pattern /Date\(([^)]+)\)/.
The exec()method accepts the source date value and tests for a match in the value. The return value of exec()is an array. In this case the second element of the results array (results[1]) holds the ticks part of the source date.

convertToJavaScriptDate()函数接受一个\/Date(ticks)\/格式的值并返回一个格式的日期字符串MM/dd/yyyy
在内部,该convertToJavaScriptDate()函数使用表示模式的正则表达式/Date\(([^)]+)\)/
exec()方法接受源日期值并测试该值是否匹配。的返回值exec()是一个数组。在这种情况下,结果数组 ( results[1])的第二个元素保存源日期的刻度部分。

For example, if the source value is \/Date(836418600000)\/then results[1]will be 836418600000.
Based on this ticks value a JavaScript Date object is formed. The Date object has a constructor that accepts the number of milliseconds since 1 January 1970.
Thus dtholds a valid JavaScript Date object.
The convertToJavaScriptDate()function then formats the date as MM/dd/yyyyand returns to the caller.

例如,如果源值\/Date(836418600000)\/然后results[1]836418600000
基于这个刻度值,一个 JavaScript 日期对象被形成。Date 对象有一个构造函数,它接受自 1970 年 1 月 1 日以来的毫秒数。
因此dt保存了一个有效的 JavaScript Date 对象。然后
convertToJavaScriptDate()函数将日期格式化为MM/dd/yyyy并返回给调用者。

You can use the convertToJavaScriptDate()function as shown below:

您可以使用convertToJavaScriptDate()如下所示的函数:

options.success = function (order) {
 alert("Required Date : " + convertToJavaScriptDate(order.RequiredDate) + ", Shipped Date : " + convertToJavaScriptDate(order.ShippedDate));
};

Although the above example uses date in MM/dd/yyyyformat, you can use other formats also once Date object is constructed.

虽然上面的例子在MM/dd/yyyy格式中使用了日期,但是一旦构建了 Date 对象,您也可以使用其他格式。

reference : Link

参考:链接

回答by chridam

You could try this:

你可以试试这个:

   _$.ajax({
        url: 'Default.aspx/GetPerson',
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            console.log(JSON.stringify(data.d));
            var src = data.d.Birthday;
            //Remove all non-numeric (except the plus)
            src = src.replace(/[^0-9 +]/g, ''); 
            //Create date
            var birthDate = new Date(parseInt(src));
            self.html(birthDate);
        }
    });

JSFiddle

JSFiddle

回答by Even Mien

If you're open to using another JavaScript library:

如果您愿意使用其他 JavaScript 库:

http://momentjs.com/docs/#/parsing/asp-net-json-date/

http://momentjs.com/docs/#/parsing/asp-net-json-date/

回答by Richard Housham

Another way of tackling this problem is to make a new element in your person class and then use that. Example

解决这个问题的另一种方法是在你的 person 类中创建一个新元素,然后使用它。例子

public class Person {
   public int Id {get;set;}
   public string Name {get;set;}
   public DateTime Birthday {get;set;}
   public string BirthdayFormat { get {
      return Birthday.toString("dd/MM/YYYY")
   }}
}

I would have thought this would be the best way as then all the formating is in one place and where possible you can use. [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/YYYY}")]

我原以为这将是最好的方法,因为那时所有的格式化都在一个地方,并且您可以在可能的情况下使用。 [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/YYYY}")]

Above the Birthday element, so that displayFor will use the correct formatting.

在生日元素上方,以便 displayFor 将使用正确的格式。