Reputation: 1412
I am trying to convert a JSON string date (in 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. What am I doing wrong? Thanks for your help.
Code Snippet:
var json = JSON.parse(resp);
var flightDate = new Date(json[i].flightDate)
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])
}
}
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"
}]
UPDATE:
JSON in this question was updated to accurately reflect what I have on my computer so the issue isn't the JSON formatting. I'm mainly interested in converting the JSON string date to JavaScript date. Please note that since this is in Google Apps Script, importing libraries (i.e. Moment.js) is not possible.
Upvotes: 0
Views: 1326
Reputation: 1200
EDIT: Now that JSON seems to be syntactically correct, I can only comment why did it print 1969-12-31.
EDIT2: According to code snippet you recently provided; (which has many syntax errors!) you are comparing flightDate string
to afterDate Date
. You should create a Date object from flightDate first, then compare accordingly.
When you call Date constructor with invalid values; most of the time it'll print out 1970-01-01 which is the epoch.
You are probably behind UTC timezone, so yours was 1969-12-31.
Upvotes: 0
Reputation: 594
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);
Upvotes: 1