0

Sample JSON:

[{"DispatchDt":"2014-05-28T01:34:00","RcvdDt":"1988-12-26T00:00:00"}]

I have this set of dates and I want to convert it to the date format (mm/dd/yyyy). How do you do this is JavaScript?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
LYKS
  • 69
  • 4
  • 13
  • 1
    possible duplicate of [How to format a JSON date?](http://stackoverflow.com/questions/206384/how-to-format-a-json-date) – xd6_ Jun 18 '14 at 02:44
  • Could you be more specific? 1) do you want the first or the second date out? So are you looking for 05/28/3014 or 12/26/1988. 2) Do you want the result in an object? In a variable? Please give expected output and we can help. – ilonabudapesti Jun 18 '14 at 02:48
  • @Monthy: the question is already specific. OP has a date that is stored in a string in a given format and they need to reformat it into `mm/dd/yyyy` – zerkms Jun 18 '14 at 02:49
  • @Monthy i think what she exactly wanna try to do is to change the format value of those datetime to date only. – Jhonathan H. Jun 18 '14 at 02:49
  • @Kaii that's easy but what makes you say that? Also the above is not fully JSON, but that's another point. – ilonabudapesti Jun 18 '14 at 02:53
  • @Monthy: "is not fully JSON" --- what do you mean by that? It's a valid JSON – zerkms Jun 18 '14 at 02:54
  • @Monthy To be more specific 1) both 2) variable :) – LYKS Jun 18 '14 at 02:56

3 Answers3

7

Unfortunately parsing and formatting dates is a weak side of javascript.

So usually for that we use the 3rd party libraries like moment.js

An example of how you would do that with moment.js:

var date = '2014-05-28T01:34:00';

var parsedDate = moment(date);

var formattedDate = parsedDate.format('MM/DD/YYYY');

Demo: http://jsfiddle.net/8gzFW/

zerkms
  • 249,484
  • 69
  • 436
  • 539
4

You may format the json string into new Date() then use js methods to get month,day,year or what exactly you need.

   //format string to datetime
   var DispatchDt = new Date(this.DispatchDt);


   // then use this methods to fetch date,month, year needed
   //getDate() // Returns the date
   //getMonth() // Returns the month
   //getFullYear() // Returns the year
    var DispatchDt_date = DispatchDt.getDate();
    var DispatchDt_month = DispatchDt.getMonth() + 1; //Months are zero based
    var DispatchDt_year = DispatchDt.getFullYear();

Sample on jsFiddle

Jhonathan H.
  • 2,734
  • 1
  • 19
  • 28
1

This would work

var a = "[{"DispatchDt":"2014-05-28T01:34:00","RcvdDt":"1988-12-26T00:00:00"}]";
var b = JSON.parse(c);
for (i in b[0]) {
  b[0][i] = b[0][i].slice(0, 9) 
}
console.log(b); // b now looks like this [ { DispatchDt: "2014-05-28", RcvDt: "1988-12-26" } ]

Please note the dates are stringified.

ilonabudapesti
  • 903
  • 1
  • 6
  • 9
  • 1. There are issues with quotes in the first line 2. `2014-05-28` is not in an expected format – zerkms Jun 18 '14 at 03:08