I would like to get the date (without timezone or time) from differently formatted strings that are passed into my function. The problem I am having is that the dates are not processing correctly due to the timezone I am in. Here is the current function I have:
function pgFormatDate(date) {
/* Via http://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date */
function zeroPad(d) {
return ("0" + d).slice(-2)
}
if (date) {
var parsed = new Date(date)
return [parsed.getUTCFullYear(), zeroPad(parsed.getMonth() + 1), zeroPad(parsed.getDate())].join("-");
} else {
return null;
}
}
And here is the makeshift test harness I have created for it (all "tests" should log true
if the function is working.
var test1Result = dateConvertsCorrectly("Fri Jul 07 2017 22:10:08 GMT-0500 (CDT)", "2017-07-07"); // Currently working and logging true, but break when I try to fix the others
var test2Result = dateConvertsCorrectly("Fri Jul 07 2017 02:10:08 GMT-0500 (CDT)", "2017-07-07"); // Currently working and logging true, but break when I try to fix the others
var test3Result = dateConvertsCorrectly("2017-07-07", "2017-07-07"); // Currently not working and logging false
var test4Result = dateConvertsCorrectly("Fri Jul 06 2017 22:10:08 GMT-0500 (CDT)", "2017-07-06"); // Currently working and logging true, but break when I try to fix the others
var test5Result = dateConvertsCorrectly("2017-07-06T02:59:12.037Z", "2017-07-06"); // Currently not working and logging false
var test6Result = dateConvertsCorrectly("2017-06-07", "2017-06-07"); // Currently not working and logging false
console.log('test 1 passed:', test1Result);
console.log('test 2 passed:', test2Result);
console.log('test 3 passed:', test3Result);
console.log('test 4 passed:', test4Result);
console.log('test 5 passed:', test5Result);
console.log('test 6 passed:', test6Result);
function pgFormatDate(date) {
/* Via http://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date */
function zeroPad(d) {
return ("0" + d).slice(-2)
}
if (date) {
var parsed = new Date(date)
return [parsed.getUTCFullYear(), zeroPad(parsed.getMonth() + 1), zeroPad(parsed.getDate())].join("-");
} else {
return null;
}
}
function dateConvertsCorrectly (input, expectedOutput) {
return pgFormatDate(input) === expectedOutput;
}
Tests 3, 5, and 6 are all failing in the CDT
timezone. But I would like the code to work regardless of timezone (I really just want to keep the year, month, and day that are submitted). Using moment hasn't worked because the dates don't fit into the accepted date types allowed by moment and I get an error, so I would like to be able to do this with vanilla javascript.
Here is the jsFiddle: https://jsfiddle.net/lukeschlangen/bkyquu7j/