【问题标题】:TypeScript Difference Between two dates in Days两个日期之间的 TypeScript 差异
【发布时间】:2023-04-08 18:23:01
【问题描述】:

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

例如,如果开始日期是 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> 

打字稿文件:

    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);
      }
    }

如果两天在同一个月,则工作正常。

提前感谢您的支持。

更新:我想出了如何解决它。一切都按预期工作,除非所选日期是该月的最后一天。现场演示如下:

The DEMO Here

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

但是当开始日期为3月31日时,它将计算为5月1日:

知道出了什么问题吗?提前致谢。

【问题讨论】:

  • 我认为只需将日期转换为毫秒,然后减去然后转换为天。可能会奏效。
  • (dateTo.valueOf() - dateFrom.valueOf()) / 86400000
  • 谢谢,我试过了,但效果不佳
  • 谢谢...我在下面尝试过,但仍然无法正常工作: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));任何建议

标签: angular typescript datetime difference


【解决方案1】:

使用 moment 的 diff 函数,您可以获得这两个日期之间适当的 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,如果仍有问题,请告诉我。

【讨论】:

  • 非常感谢您的支持。我更新了我的代码,它实际上正在工作。但是,当我选择不同月份的日期时遇到的问题。例如,当我从同一个月中选择两个日期时,差异计算正确。但是,当我选择两个不同的日期时,数据已损坏。可以在以下位置找到现场演示:stackblitz.com/github/abdelrahman84/…
  • 感激不尽。这解决了我的问题,一切都按预期工作。度过美好的一天
【解决方案2】:

对于日期和时间计算用户 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

【讨论】:

    【解决方案3】:

    使用此代码:

    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);
    

    【讨论】:

      猜你喜欢
      • 2011-10-29
      • 1970-01-01
      • 2014-02-12
      • 2015-09-14
      • 2015-06-21
      • 2020-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多