Racialz Racialz - 7 months ago 20
Javascript Question

Getting wrong results parsing dates in JavaScript

I'm starting with a json string that looks like:

["2016-05-28", "2016-05-29", "2016-05-30", "2016-05-31"]


I'm trying to convert this into
Saturday 5/28
Sunday 5/29
.

I looked at these answers and tried to implement the same:
Why does Date.parse give incorrect results? and
Convert date in string to date object for inserting in database.

But I'm getting the wrong day output. 5/28 comes out as
Tuesday, 5/28
when it is a Saturday.

JSFiddle: https://jsfiddle.net/pum40hyx/

Here's my code where I convert the date into my desired string:

function convertToNiceDate(inputDate)
{
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var splitString = inputDate.split("-");

currentDate = new Date(splitString[0], splitString[1], splitString[2]);
var day = currentDate.getDate();
var month = currentDate.getMonth();

//this is the problematic line!
var dayOfWeek = days[currentDate.getDay()];

var dateString = dayOfWeek + ", " + month + "/" + day;
return dateString;
}

Answer

The range for months is 0-11 when constructing a new Date using the new Date(year, month[, day[, ...) format. So January should be 0, not 1 when the string is split.

month: Integer value representing the month, beginning with 0 for January to 11 for December.

Here's a hacky solution to prove the point:

function convertToNiceDate(inputDate)
{
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    var splitString = inputDate.split("-");

    currentDate = new Date(splitString[0], +splitString[1]-1, splitString[2]);
    var day = currentDate.getDate();
    var month = currentDate.getMonth() + 1;

    //this is the problematic line!
    var dayOfWeek = days[currentDate.getDay()];

    var dateString = dayOfWeek + ", " + month + "/" + day;
    return dateString;
}

document.body.innerHTML = convertToNiceDate('2016-01-01');

You can also do the following:

function convertToNiceDate(inputDate) {
  var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  var splitString = inputDate.split("-");

  currentDate = new Date(inputDate);
  var day = currentDate.getUTCDate();
  var month = currentDate.getUTCMonth() + 1;

  //this is the problematic line!
  var dayOfWeek = days[currentDate.getUTCDay()];

  var dateString = dayOfWeek + ", " + month + "/" + day;
  return dateString;
}

document.body.innerHTML = convertToNiceDate('2016-01-01');