当我尝试减去
时 Wed Dec 06 2017 15:58:59 GMT+0530 (India Standard Time)
减去Tue Nov 28 2017 00:00:00 GMT+0530 (India Standard Time)
,即将到来的答案是 -22
但答案应为 6
出了什么问题,下面是我的page.ts
代码:
this.tt = new Date();
this.tt1 = this.datePipe.transform(this.tt,'dd/mm/yyyy');
console.log(this.ent[0],"server DATE");
// in console we see this - 28-NOV-17 server DATE
var firstDate= new Date(this.ent[0]); //Jan 01 2017 00:00:00
var secondDate = new Date();//Jan 04 2017 00:00:00
console.log(firstDate);
// answer in console - Tue Nov 28 2017 00:00:00 GMT+0530 (India Standard Time)
console.log(secondDate);
//answer in console - Wed Dec 06 2017 15:58:59 GMT+0530 (India Standard Time)
console.log(secondDate.getDate() - firstDate.getDate() );
//answer in console - -22
date.getDate()给出日期的" dd"(在您的情况6和28中,将结果解释为-22)。我对预期结果有点困惑6.所以也许我的答案不适合您。但是,我要做的是转换日期,进行缩写并将其转换回天数。
so
Math.Floor((secondDate.getTime() - firstDate.getTime()) / 86400000);
(86400000 being 1000 (milliseconds) * 3600 (seconds in an hour) * 24 (number of hours in a day)
您可以将日期转换为时间戳并减去时间戳,您将在Millis中获得结果的日子,现在将其转换为天
getTimestamp(dateParam:string):string{
var date = new Date(dateParam); // some mock date
var milliseconds = date.getTime();
return milliseconds.toString();
}
var one_day=1000*60*60*24;
console.log(Math.ceil(getTimestamp(secondDate) - getTimestamp(firstDate))/(one_day) );