Stange javascript Date 在特定日期的行为 [英] Stange javascript Date behaviour on particular dates
问题描述
我注意到 javascript 在管理此特定日期时的一种奇怪行为
i noticed a strange behave of javascript on manging this particular Date
"31-12-2017 23:59:59"
我有一个 API,我调用它并将一些日期作为字符串返回给我,我必须使用 js 将它们转换为 Date.
i have an API which i call and returns me some date as String, and i have to cast them to Date using js.
我的代码就是这样
while (i<array.length){
array[i].start_date = new Date (array[i].start_date);
array[i].start_date.setHours(array[i].start_date.getHours()+1);
array[i].start_date = $filter('date')(array[i].start_date, "dd-MM-yyyy HH:mm:ss");
array[i].end_date = new Date (array[i].end_date);
array[i].end_date.setHours(array[i].end_date.getHours()+1);
array[i].end_date = $filter('date')(array[i].end_date, "dd-MM-yyyy HH:mm:ss");
$scope.insSupplies.push(array[i]);
i++;
};
其中 array 是我正在质疑的 API.
where array is the API i'm questioning.
这里的问题是当我的代码尝试这个时
The problem here is that when my code tries this
array[i].end_date = new Date (array[i].end_date);
在这一天
"31-12-2017 23:59:59"
array[i].end_date
变成 Invalid Date
这是怎么发生的?
var date = "31-12-2017 23:59:59"
var dateSplitted = date.split("-");
var dateInverted = dateSplitted[1] +"-" +dateSplitted[0] +"-"+dateSplitted[2];
dateSplitted = dateInverted.split(" ");
alert(dateSplitted[0]+"T"+dateSplitted[1]+"Z");
alert(new Date(dateSplitted[0]+"T"+dateSplitted[1]+"Z"));
我实现了这个粗略的方法来解析我的日期,但我不明白怎么回事有什么帮助吗?
I implemented this rough method to parse my date, but i don't get how is wrong Any help?
推荐答案
我不知道这里发生了什么问题.但解决方案是您的月份和日期格式被错误地转换.
I don't know what is the issue going on here. But the solution is your month and date format is wrongly placed to convert.
您的日期格式应为 12-31-2017 23:59:59
而不是 31-12-2017 23:59:59
.比如mm/dd/yyyy
.可能它的工作原理类似于您的浏览器默认日期格式.
Your date format should be 12-31-2017 23:59:59
instead of 31-12-2017 23:59:59
. like mm/dd/yyyy
. may be it's works like your browser default date format.
您可以在警报结果下方查看此内容.
you can check this below alert results.
alert(new Date("12-31-2017 23:59:59"))// this is a correct format.
alert(new Date("31-12-2017 23:59:59"))// here `31` is month. The default month count is 12. but here it's automatically add 19 months into 12 month(31-12). So it will go to future year.
alert(new Date("13-12-2017 23:59:59"))// here you can check the result of Jan month 2018
您应该在转换前交换月份和日期.试试下面的代码
You should swap the month and date before convert. try this below code
var date= "31-12-2017 23:59:59".split("-");
var newDate = date[1] +"-" +date[0] +"-" +date[2];
alert(new Date(newDate));
这篇关于Stange javascript Date 在特定日期的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!