错误的结果在JavaScript中解析日期

时间:2016-05-03 02:58:51

标签: javascript json date

我从一个类似于["2016-05-28", "2016-05-29", "2016-05-30", "2016-05-31"]

的json字符串开始

我试图将其转换为Saturday 5/28 Sunday 5/29

我查看了这些答案,并试图实现相同的目标: Why does Date.parse give incorrect results?Convert date in string to date object for inserting in database

但是我得错了一天的输出。 5/28在星期六时显示为Tuesday, 5/28

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

这是我的代码,我将日期转换为我想要的字符串:

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;
}

3 个答案:

答案 0 :(得分:5)

使用0-11格式构建新Date时,月份范围为new Date(year, month[, day[, ...)。因此,当字符串被拆分时,1月应为0,而不是1

  

<强>月:       表示月份的整数值,从1月的0开始到12月的11。

这是一个证明重点的黑客解决方案:

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');

您还可以执行以下操作:

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');

答案 1 :(得分:0)

使用setter(也许你应该在所有这些上使用parseInt):

var currentDate //with var
   = new Date();
   currentDate.setFullYear(splitString[0]);
   currentDate.setDate(splitString[2]);
   currentDate.setMonth(parseInt(splitString[1])-1);

   //do something with your date object

答案 2 :(得分:0)

我刚刚发现,当你分割字符串时,你的日期月份(这里是splitString [1])总是太过分了。我认为这是因为它需要月份(5)的数组,这将代表六月而不是五月(它从一月份的0开始)。 尝试使用:

currentDate = new Date(splitString.toString());