为什么我得到一个错误的约会
我想将给定日期从dd.mm.yyyy转换为yyyy-mm-dd。我试过下面的代码。但如果我给的是22.10.2018剧本,则返回2018-11-21T23:00:00.000Z。但为什么呢?
我尝试过的事情:
I would like to convert a given date from dd.mm.yyyy to yyyy-mm-dd. I tried the Code below. But if i'm giving a "22.10.2018" the script Returns "2018-11-21T23:00:00.000Z". But why?
What I have tried:
function hasError() {
function toDate(datestr) {
var parts = datestr.split(".")
return new Date(parts[2], parts[1], parts[0])
}
var comparestart = toDate("22.10.2018");
var compareende = toDate("02.11.2018");
console.log(comparestart);
console.log(compareende);
if(comparestart >= compareende) {
console.log(true);
} else {
console.log(false);
}
}
hasError();
有2个问题使用代码:
1 - 日期对象假设月份编号从0开始,而不是1.行:
There are 2 issues with the code:
1 - "Date" object asumes month number to start in 0, not 1. The line:
new Date(parts[2], parts[1], parts[0])
应为:
should be:
new Date(parts[2], parts[1] - 1, parts[0])
2 - 请注意新日期以当地时区为单位(也受夏令时影响)。在这种情况下,新日期(年,月-1,日)在您当地的00:00:00时间创建日期。对于任何其他时区,这当然是不同的当地时间。西边的任何位置都是您之前的日期。
为避免出现时区问题,请始终使用UTC功能。例如:
2 - Notice "new Date" asumes hour to be in your local timezone (also affected by daylight saving). In this case, new Date(year, month-1, day) creates a date in your local 00:00:00 time. Which of course would be a different local hour for any other timezone. Any location on the west to you would be the previous date.
To avoid timezone issues, use always UTC functions. Eg:
new Date(Date.UTC(parts[2], parts[1] - 1, parts[0]))
您好,非常感谢您的帮助。最后我使用了该代码:
Hello, thank you very much for all your help. Finally i used that Code:
function hasError() {
function toDate(datestr) {
var parts = datestr.split(".")
return new Date(parts[2], parts[1] -1, parts[0]).toLocaleString('de-DE', {timeZone: 'Europe/Berlin'})
}
var comparestart = toDate("
Start);
var compareende = toDate(
Start"); var compareende = toDate("