16

Introduction:

I have a WebMethod on my ASP.NET page which returns a Person object. One of the fields is Birthday which is a DateTime property.

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 Person object.

Ajax call

// 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.

asked Dec 5, 2014 at 11:15
4
  • try this code in your webmethod Birthday = new DateTime(1988, 9, 13).ToLongDateString(); Commented Dec 5, 2014 at 11:23
  • Birthday is of type DateTime so I can't parse it to a string Commented Dec 5, 2014 at 11:24
  • Follow this blog Commented Dec 5, 2014 at 11:25
  • @ArunPrasanth works like a charm, if you want post an answer for it! Commented Dec 5, 2014 at 11:33

4 Answers 4

26

Use convertToJavaScriptDate() function that does this for you:

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/yyyy format.
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.

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 dt holds a valid JavaScript Date object.
The convertToJavaScriptDate() function then formats the date as MM/dd/yyyy and returns to the caller.

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

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

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

reference : Link

answered Dec 5, 2014 at 11:42

3 Comments

Here is the version with time included: function ToJavaScriptDateTime(value) { var pattern = /Date\(([^)]+)\)/; var results = pattern.exec(value); var dt = new Date(parseFloat(results[1])); return dt.getHours() + ":" + dt.getMinutes() + " " + ('0' + dt.getDate()).slice(-2) + "." + ('0' + (dt.getMonth() + 1)).slice(-2) + "." + dt.getFullYear(); }
ive just tried ur method and i got an error jQuery.Deferred exception: Cannot read property '1' of null TypeError: Cannot read property '1' of null
Can u provide me a jsfiddle??
1

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

answered Dec 5, 2014 at 11:29

Comments

1

If you're open to using another JavaScript library:

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

answered Mar 17, 2015 at 14:22

1 Comment

This is good, if you intend to use the date/time in the javascript ie. some manipulation
1

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

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}")]

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

answered Feb 1, 2017 at 15:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.