var obj = DateTime.Now;
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.Serialize(obj).Dump();
Now the problem I am facing is how to create a Date object from this in JavaScript.
All I could find was incredible regex solution (many containing bugs).
It is hard to believe there is no elegant solution as this is all in JavaScrip, I mean JavaScript code trying to read JSON (JavaScript Object Notation) which is supposed to be a JavaScript code and at this moment it turns out it's not cause JavaScript cannot do a good job here.
I've also seen some eval solutions which I could not make to work (besides being pointed out as security threat).
Is there really no way to do it in an elegant way?
Similar question with no real answer:
How to parse ASP.NET JSON Date format with GWT
–
The JSON.parse
function accepts an optional DateTime reviver function. You can use a function like this:
dateTimeReviver = function (key, value) {
var a;
if (typeof value === 'string') {
a = /\/Date\((\d*)\)\//.exec(value);
if (a) {
return new Date(+a[1]);
return value;
Then call
JSON.parse(somejsonstring, dateTimeReviver);
And your dates will come out right.
–
–
–
–
As he says: The substr function takes out the "/Date(" part, and the parseInt function gets the integer and ignores the ")/" at the end. The resulting number is passed into the Date constructor.
Another option is to simply format your information properly on the ASP side such that JavaScript can easily read it. Consider doing this for your dates:
DateTime.Now()
Which should return a format like this:
7/22/2008 12:11:04 PM
If you pass this into a JavaScript Date
constructor like this:
var date = new Date('7/22/2008 12:11:04 PM');
The variable date
now holds this value:
Tue Jul 22 2008 12:11:04 GMT-0700 (Pacific Daylight Time)
Naturally, you can format this DateTime
object into whatever sort of string/int the JS Date
constructor accepts.
–
–
–
If you use the JavaScript style ISO-8601 date in JSON, you could use this, from MDN:
const jsonDate = (new Date()).toJSON();
const backToDate = new Date(jsonDate);
console.log(jsonDate); //2015-10-26T07:46:36.611Z
To create an ISO-8601 date string:
myDate.toISOString()
–
–
–
–
–
–
I know this is a very old thread but I wish to post this to help those who bump into this like I did.
if you don't care about using a 3rd party script, you can use moment,js
Then you can use .format() to format it to anything you want it to.
Dates are always a nightmare. Answering your old question, perhaps this is the most elegant way:
eval(("new " + "/Date(1455418800000)/").replace(/\//g,""))
With eval we convert our string to javascript code. Then we remove the "/", into the replace function is a regular expression. As we start with new then our sentences will excecute this:
new Date(1455418800000)
Now, one thing I started using long time ago, is long values that are represented in ticks... why? well, localization and stop thinking in how is date configured in every server or every client. In fact, I use it too in databases.
Perhaps is quite late for this answer, but can help anybody arround here.
–
The answer to this question is, use nuget to obtain JSON.NET then use this inside your JsonResult
method:
JsonConvert.SerializeObject(/* JSON OBJECT TO SEND TO VIEW */);
inside your view simple do this in javascript
:
JSON.parse(/* Converted JSON object */)
If it is an ajax call:
var request = $.ajax({ url: "@Url.Action("SomeAjaxAction", "SomeController")", dataType: "json"});
request.done(function (data, result) { var safe = JSON.parse(data); var date = new Date(safe.date); });
Once JSON.parse
has been called, you can put the JSON date into a new Date
instance because JsonConvert
creates a proper ISO time instance
AngularJS couldn't parse .NET JSON date /Date(xxxxxxxxxxxxx)/
string either..
I side stepped this issue by formatting the date to its ISO 8601 string representation instead of dumping the Date
object directly...
Here is a sample of ASP.NET MVC code..
return Json(new {
date : DateTime.Now.ToString("O") //ISO 8601 Angular understands this format
I tried RFC 1123
but it doesn't work.. Angular treats this as string instead of Date.
return Json(new {
date : DateTime.Now.ToString("R") //RFC 1123 Angular won't parse this
I've not used .Net for things like this. If you were able to get it to print something like the following out it should work.
Note, unless you're parsing that JSON string by some other means or only expect users to have modern browers with a built in JSON parser you need to use a JS framework or JSON2 to parse the JSON string outputted by the server into a real JSON object.
// JSON received from server is in string format
var jsonString = '{"date":1251877601000}';
//use JSON2 or some JS library to parse the string
var jsonObject = JSON.parse( jsonString );
//now you have your date!
alert( new Date(jsonObject.date) );
–
–
var fullDate = new Date(parseInt(jsonDate.substr(6)));
var twoDigitMonth = (fullDate.getMonth() + 1) + ""; if (twoDigitMonth.length == 1) twoDigitMonth = "0" + twoDigitMonth;
var twoDigitDate = fullDate.getDate() + ""; if (twoDigitDate.length == 1) twoDigitDate = "0" + twoDigitDate;
var currentDate = twoDigitMonth + "/" + twoDigitDate + "/" + fullDate.getFullYear();
return currentDate;
As Callum mentioned, for me, the best way is to change the Controller method to string instead of JsonResult".
public string GetValues()
MyObject.DateFrom = DateTime.Now;
return JsonConvert.SerializeObject(MyObject);
From the ajax method you can do something like this
$.ajax({
url: "/MyController/GetValues",
type: "post",
success: function (data) {
var validData = JSON.parse(data);
//if you are using datepicker and you want set a format
$("#DateFrom").val($.datepicker.formatDate("dd/mm/yy", new Date(validData.DateFrom)));
// if you want the date as returned
$("#DateFrom").val(new Date(validData.DateFrom))
using eval function works just have to remove the forward slash at front and back.
var date1 = "/Date(25200000)/"
eval("new " + date1.substring(1, date1.length - 1));
yields Thu Jan 01 1970 00:00:00 GMT-0700 (US Mountain Standard Time)
I ran into an issue with external API providing dates in this format, some times even with UTC difference info like /Date(123232313131+1000)/
. I was able to turn it js Date
object with following code
var val = '/Date(123232311-1000)/';
var pattern = /^\/Date\([0-9]+((\+|\-)[0-9]+)?\)\/$/;
var date = null;
// Check that the value matches /Date(123232311-1000)/ format
if (pattern.test(val)) {
var number = val.replace('/Date(', '',).replace(')/', '');
if (number.indexOf('+') >= 0) {
var split = number.split('+');
number = parseInt(split[0]) + parseInt(split[1]);
} else if (number.indexOf('-') >= 0) {
var split = number.split('-');
number = parseInt(split[0]) - parseInt(split[1]);
} else {
number = parseInt(number);
date = new Date(number);
like @jacob have said here answer , the reviver param in the JSON.parse could be a good soluction :)
I tried something like this and i receive a good result
function dateTimeReviver(key: string, value: any) {
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) {
return new Date(value);
return value;
–
// formats a .net date into a javascript compatible date
function FormatJsonDate(jsonDt)
var MIN_DATE = -62135578800000; // const
var date = new Date(parseInt(jsonDt.substr(6, jsonDt.length-8)));
return date.toString() == new Date(MIN_DATE).toString() ? "" : (date.getMonth() + 1) + "\\" + date.getDate() + "\\" + date.getFullYear();
var fullDate = new Date(parseInt(jsonDate.substr(6)));
var twoDigitMonth = (fullDate.getMonth() + 1) + ""; if (twoDigitMonth.length == 1) twoDigitMonth = "0" + twoDigitMonth;
var twoDigitDate = fullDate.getDate() + ""; if (twoDigitDate.length == 1) twoDigitDate = "0" + twoDigitDate;
var currentDate = twoDigitMonth + "/" + twoDigitDate + "/" + fullDate.getFullYear();
return currentDate;
//Use this function
var objDate=parseJsonDate("\/Date(1443812400000)\/");
alert(objDate);
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.