当我尝试减去
时 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
请告知我如何才能得到理想的结果,谢谢您的时间:)
答案 0 :(得分:0)
Date.getDate()给出" dd"日期(在你的情况下6和28,解释结果为-22)。 我对预期的结果有点困惑是6.所以也许我的答案不适合你。然而,我要做的是及时转换日期,做减法并将其转换回天数。
所以
Math.Floor((secondDate.getTime() - firstDate.getTime()) / 86400000);
(86400000 being 1000 (milliseconds) * 3600 (seconds in an hour) * 24 (number of hours in a day)
答案 1 :(得分:0)
您可以将这两个日期转换为时间戳,然后减去您将获得结果天数的时间戳,以毫秒为单位将其转换为天数
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) );