Uzair Khan
Uzair Khan

Reputation: 2970

Datetime stamp to date in jquery

I have a datetime property in my model which is sent as json object in ajax's success function. The property value is '/Date(1484162865865)/'. How do I convert this to date time in jquery? Tried this but it did not get me results.

var d = new Date(createdDateTimeStamp);
    // Date
    var da = d.getDate();       //day
    var mon = d.getMonth() + 1; //month
    var yr = d.getFullYear();   //year
    var thisDay = da + "/" + mon + "/" + yr;

    var dateTime = {
        fullDate: thisDay,
    };

Thanks in advance.

Upvotes: 0

Views: 224

Answers (3)

RKS
RKS

Reputation: 1410

You can use the following.

Here, ticks is the value 1484162865865 that you are getting. ticks refers to the number of milliseconds passed since 01/01/1970.

function getMMDDYY(ticks) {
  var date = new Date(ticks);
  var mm = date.getMonth()+1;
  var dd = date.getdate();
  var yy = new String(date.getFullYear()).substring(2);
  if (mm < 10) mm = "0"+mm;
  if (dd < 10) dd = "0"+dd;
  return mm+dd+yy;
}

Hope this helps.

Upvotes: 1

Uzair Khan
Uzair Khan

Reputation: 2970

Thanks itzikb and RKS, but the issue was in sending datetime using json to ajax success.

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

I sent my datetime, added regex to take out ticks and converted to date.

Upvotes: 0

Itzik.B
Itzik.B

Reputation: 1086

there is no option called createdDateTimeStamp inside Date class.

This is the fixed code:

var d = new Date();
// Date
    var da = d.getDate();       //day
    var mon = d.getMonth() + 1; //month
    var yr = d.getFullYear();   //year
    var thisDay = da + "/" + mon + "/" + yr;

    var dateTime = {
        fullDate: thisDay,
    };
   alert(dateTime.fullDate)

Good Luck!

Upvotes: 1

Related Questions