TypeScript在天中两个日期之间的差异

时间:2019-03-09 11:02:51

标签: angular typescript

我正在尝试计算几天内两个日期之间的差异。但是,当两个日期位于不同的月份时,上个月的日期将被丢弃。

例如,如果开始日期为3月31日,结束日期为4月1日,则差异为0。

HTML:

    <ngb-datepicker #dp (select)="onDateSelection($event)" [displayMonths]="2" [dayTemplate]="t" outsideDays="hidden">
    </ngb-datepicker>

    <ng-template #t let-date let-focused="focused">
      <span class="custom-day"
            [class.focused]="focused"
            [class.range]="isRange(date)"
            [class.faded]="isHovered(date) || isInside(date)"
            (mouseenter)="hoveredDate = date"
            (mouseleave)="hoveredDate = null">
        {{ date.day }}
      </span>
    </ng-template>

    <p>Number of selected dates: {{DiffDate}}</p>


    <pre>From: {{ fromDate | json }} </pre>
    <pre>To: {{ toDate | json }} </pre> 

Typsript File:

    import {Component} from '@angular/core';
    import {NgbDate, NgbCalendar} from '@ng-bootstrap/ng-bootstrap';

    @Component({
      selector: 'ngbd-datepicker-range',
      templateUrl: './datepicker-range.html',
      styles: [`
        .custom-day {
          text-align: center;
          padding: 0.185rem 0.25rem;
          display: inline-block;
          height: 2rem;
          width: 2rem;
        }
        .custom-day.focused {
          background-color: #e6e6e6;
        }
        .custom-day.range, .custom-day:hover {
          background-color: rgb(2, 117, 216);
          color: white;
        }
        .custom-day.faded {
          background-color: rgba(2, 117, 216, 0.5);
        }
      `]
    })
    export class NgbdDatepickerRange {

      hoveredDate: NgbDate;

      fromDate: NgbDate;
      toDate: NgbDate;
      DiffDate;
      enddate;
      startDate;

      constructor(calendar: NgbCalendar) {
        this.fromDate = calendar.getToday();
        this.toDate = calendar.getNext(calendar.getToday(), 'd', 10);
      }

      onDateSelection(date: NgbDate) {
        if (!this.fromDate && !this.toDate) {
          this.fromDate = date;
        } else if (this.fromDate && !this.toDate && date.after(this.fromDate)) {
          this.toDate = date;
        } else {
          this.toDate = null;
          this.fromDate = date;
        }
        this.enddate=new Date (this.toDate.year,this.toDate.month,this.toDate.day);

        this.startDate=new Date (this.fromDate.year,this.fromDate.month,this.fromDate.day);

        this.DiffDate=Math.floor((Date.UTC(this.enddate.getFullYear(),this.enddate.getMonth(),this.enddate.getDate())-Date.UTC(this.startDate.getFullYear(),this.startDate.getMonth(),this.startDate.getDate()) )/(1000 * 60 * 60 * 24));
        //this.DiffDate=(this.DiffDate/86400000);

      }

      isHovered(date: NgbDate) {
        return this.fromDate && !this.toDate && this.hoveredDate && date.after(this.fromDate) && date.before(this.hoveredDate);
      }

      isInside(date: NgbDate) {
        return date.after(this.fromDate) && date.before(this.toDate);
      }

      isRange(date: NgbDate) {
        return date.equals(this.fromDate) || date.equals(this.toDate) || this.isInside(date) || this.isHovered(date);
      }
    }

如果同一个月有两天,则可以正常工作。

提前感谢您的支持。

更新:我想出了解决方法。一切都按预期工作,除非所选的日期是月份的最后一天。实时演示可在下面找到:

https://stackblitz.com/github/abdelrahman84/Vacation-Planner-Angular?fbclid=IwAR2DBGEyLKUReyLx0LLnmnSaOp3BYVjOQvZJdQCvaHGlSTXHkb4BPg0Ymt4

例如,开始日期:3月19日,结束日期:3月21日。相差2天。

但是,当选择的开始日期为3月31日时,则计算为5月1日:

有什么想法吗?预先感谢。

3 个答案:

答案 0 :(得分:0)

使用时刻的差异函数,您可以在这两个日期之间获得正确的1天差异。

this.firstDate = moment('2019/03/31');
this.secondDate = moment('2019/04/01');
this.diffInDays = Math.abs(this.firstDate.diff(this.secondDate, 'days')); 

请参见此stackblitz进行演示。

更新

我分叉了您的stackblitz。通常会创建两个新功能并清理一些重复项。

NgbDate具有年,月和日的三个属性。重要的是该月从1开始(对于JS本地Date对象不是从零开始)。请参阅NgbDate文档here

  private createDateFromNgbDate(ngbDate: NgbDate): Date {
    const date: Date = new Date(Date.UTC(ngbDate.year, ngbDate.month-1, ngbDate.day));  
    return date;
  }

还有一个单独的函数可以像这样计算几天的差异:

private calcDaysDiff(): number {
    const fromDate: Date = this.createDateFromNgbDate(this.fromDate);
    const toDate: Date = this.createDateFromNgbDate(this.toDate);  
    const daysDiff = Math.floor(Math.abs(<any>fromDate - <any>toDate) / (1000*60*60*24));
    return daysDiff;
  }

检查更新的stackblitz,如果您仍然遇到问题,请告诉我。

答案 1 :(得分:0)

用于日期和时间计算的用户Moment.js。在您的情况下,请在Moment.js https://momentjs.com/docs/#/displaying/difference/

中使用差异方法
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

答案 2 :(得分:0)

使用此代码:

const oneday = 24 * 60 * 60 * 1000;
const momentDate = new Date(this.applicationData.businessProfile.registration_date); // Replace event.value with your date value
const formattedDate = moment(momentDate).format("YYYY-MM-DD");
const formattedDatecurrent = new Date(this.now);
this.applicationData.businessProfile.registration_date=formattedDate;
console.log(formattedDate);

console.log(formattedDatecurrent);

const Difference_In_Time = Math.round(Math.abs((Number(momentDate)  - Number(formattedDatecurrent) )/oneday));
console.log(Difference_In_Time);