Kea*_*nge 1 javascript json date
我从json字符串开始,看起来像: ["2016-05-28", "2016-05-29", "2016-05-30", "2016-05-31"]
我正在尝试将其转换为Saturday 5/28 Sunday 5/29.
我查看了这些答案并试图实现相同的目的: 为什么Date.parse会给出不正确的结果?并将 字符串中的日期转换为日期对象以插入数据库.
但我得到了错误的一天输出.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;
}
Run Code Online (Sandbox Code Playgroud)
几个月的范围是使用格式0-11构建新Date的时间new Date(year, month[, day[, ...).所以1月应该是0,而不是1字符串分裂时.
month: 表示月份的整数值,从1月的0开始到12月的11.
这是一个证明这一点的hacky解决方案:
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');Run Code Online (Sandbox Code Playgroud)
您还可以执行以下操作:
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');Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |