fragilewindows fragilewindows - 2 months ago 14
Javascript Question

Convert JSON string date to JavaScript and check if after a specific date (Google Apps Script)

I am trying to convert a JSON string date (using Google Apps Script) to JavaScript date object and then check to see if that date is after another date but I can't get it to work.

I tried using the suggestion here. but my output is incorrect. I tried using a library like Moment.js or Datejs but I don't think it's possible with Google Apps Script.




Code Snippet:

var json = JSON.parse(resp);

var flightDate = new Date(json[i].flightDate)


Output:

1969-12-31


JSON:

[{"flightDate": "2013-03-01",
"traveler": "Paul Carter",
"flight": "JetBlue",
"destination": "Australia"
},
{"flightDate": "1997-02-18",
"traveler": "Paul Carter",
"flight": "American Airlines",
"destination": "Australia"
},
{"flightDate": "2004-05-25",
"traveler": "Paul Carter",
"flight": "JetBlue",
"destination": "Chile"
},
{"flightDate": "1995-08-05",
"traveler": "Paul Carter",
"flight": "United",
"destination": "Ireland"
}]





I'm also trying to check if the date is after a certain date:

Code Snippet:

for (i = 0; i < json.length; i++ {

flightDate = json[i].flightDate
traveler = json[i].traveler
flight = json[i].flight
destination = json[i].destination

var afterDate = new Date('1997-07-30')

if (flightDate >= afterDate) {
output.push ([flightDate, traveler, flight, destination])
}
}


What am I doing wrong? Thanks for your help.

Answer

First of all, if that is a copy of your json then your parse will not work because there are missing , in it.

After correcting your json, then you can use the Arrays filter to get the flights after a certain date.

var data = [{
  flightDate: "2013-03-01",
  traveler: "Paul Carter",
  flight: "JetBlue",
  destination: "Australia"
}, {
  flightDate: "1997-02-18",
  traveler: "Paul Carter",
  flight: "American Airlines",
  destination: "Australia"
}, {
  flightDate: "2004-05-25",
  traveler: "Paul Carter",
  flight: "JetBlue",
  destination: "Chile"
}, {
  flightDate: "1995-08-05",
  traveler: "Paul Carter",
  flight: "United",
  destination: "Ireland"
}];

var afterDate = new Date("2000-01-01");
var flightsAfter = data.filter(function(flight) {
  return new Date(flight.flightDate) >= afterDate;
});

console.log(flightsAfter);

Comments