-1

I have a json response like this :

{
 "NO_INSPECTION": "55",
 "NO_SURAT": "00055",
 "DATE_OF_DESCRIPTION": "2015-12-21 03:08:24"
}

How can I convert the data in "DATE_OF_DESCRIPTION" Into date and time. Date should be dd-mm-yyy format and time should be in HH:mm format. (A sample value of DATE_OF_DESCRIPTION is 2015-12-21 03:08:24)

I have tried new Date(response.DATE_OF_DESCRIPTION); but no success. How can I achieve this?

Fadly Dzil
  • 2,154
  • 3
  • 34
  • 85
  • 1
    Possible duplicate of [javascript Date.parse](http://stackoverflow.com/questions/2587345/javascript-date-parse) – Ivar Dec 22 '15 at 09:54

2 Answers2

0

JavaScript has a fixed date format and you can change it, thus the Date object won't help you this time. As I see it, you want to split that date, so it's pretty easy if you provide it in this format "dd-mm-yyy HH:mm":

response.DATE_OF_DESCRIPTION = response.DATE_OF_DESCRIPTION.split(" "); // date and time are separated by an space
var date = response.DATE_OF_DESCRIPTION[0];
var time = response.DATE_OF_DESCRIPTION[1];

BTW, if you want to parse a date in a specified format, why don't you use any library for that? Many of them are almost as reliable and fast as native methods. Give them a try ;)

You could also format the date, so it fits the JS specs but, why reinvent the wheel? Libraries will do this for you and you'll get optimal cross-browser results!

I've googled "javascript date parsing library" and this is what I've found:

http://momentjs.com/ <--- I think that's what you're looking for!

BrainOverflow
  • 513
  • 1
  • 3
  • 11
0

Without the use of other libraries and assuming the output will always be zero-padded and the same length, I would do this:

var response = {
  DATE_OF_DESCRIPTION: "2015-12-21 03:08:24"
}

var raw = response.DATE_OF_DESCRIPTION;

var datePart = raw.split(' ')[0];
var timePart = raw.split(' ')[1];

var year = datePart.substring(0, 4);
var month = datePart.substring(5, 7);
var day = datePart.substring(8, 10);

var hours = timePart.substring(0, 2);
var minutes = timePart.substring(3, 5);

// NOTE: Month is 0 indexed
var date = new Date(year, month - 1, day);
var dateTime = new Date(year, month - 1, day, hours, minutes);

console.log(date);
console.log(dateTime);

This gives the output

Mon Dec 21 2015 00:00:00 GMT+1000 (E. Australia Standard Time)
Mon Dec 21 2015 03:08:00 GMT+1000 (E. Australia Standard Time)
(I'm from Australia, so your timezone will vary)
JosephGarrone
  • 4,081
  • 3
  • 38
  • 61