-2

I'm returning a date to a text box using JSON, this means my date is returned as a string like this:

/Date(1335205592410)

Can anyone tell me how I can access this date from my textbox and convert it to a useable date format i.e. DD/MM/YYYY There are many guides online but most of them suggest using substr(6), with my value being in a textbox I'm not sure how I'd use that approach. I access my textbox like so:

function dateChange() {
    var date_box = document.getElementById('date').value;
    ...
    ... Code to populate textbox ...
    ...
}

The textbox is a generic html textbox, when the above function runs it populates it with the JSON date string.

<input id="date" name="date" />

I need help getting the date value from the textbox and then converting it to a useable date. Can anyone help me out?

Many thanks

Yanayaya
  • 2,044
  • 5
  • 30
  • 67
  • 1
    seems like something like that was explained here,, http://stackoverflow.com/questions/847185/convert-a-unix-timestamp-to-time-in-javascript – Vlad Krasovsky May 25 '16 at 15:46
  • You seem to be asking two questions: How to convert a "JSON date" to a proper date value and how to format date values? I'm pretty sure both of them have been asked and answered multiple times. – Felix Kling May 25 '16 at 15:48
  • @Yanayaya, if some of the answers help you, you can let others know. – jherax May 25 '16 at 17:16
  • 1
    Possible duplicate of [ASP.NET MVC JsonResult Date Format](http://stackoverflow.com/questions/726334/asp-net-mvc-jsonresult-date-format) –  May 25 '16 at 23:22

2 Answers2

0

Does this work ok?

var date = new Date(1335205592410);
var day = "0" + date.getDate();
var month = "0" + date.getMonth();
var year = date.getFullYear();

var formattedDate = day.substr(-2) + '/' + month.substr(-2) + '/'  + year;
alert(formattedDate);
Gadget
  • 413
  • 2
  • 7
0

Microsoft .Net handles this date format, you can overcome by gettings the miliseconds inside de Date string.

implementation

var convertMSDate = (function() {
  var pattern = /Date/,
      replacer = /\D+/g;
  return function(date) {
    if (typeof date === "string" && pattern.test(date)) {
      date = +date.replace(replacer, "");
      date = new Date(date);
      if (!date.valueOf()) {
        throw new Error("Invalid Date: " + date);
      }
    }
    return date;
  }
}());

usage

var date = '/Date(1335205592410)';
console.log(convertMSDate(date));

// use ISO 8601 format 
date = convertMSDate(date);
console.log(date.toISOString());

// get date parts
var year = date.getFullYear(),
    month = date.getMonth() + 1,
    day = date.getDate();

console.log([day, month, year].join('/'));
jherax
  • 5,238
  • 5
  • 38
  • 50