首页 > 解决方案 > 角度材料 dateAdapter 不会将不同的小时/分钟/秒视为不同的日期

问题描述

我正在为有角材料 DatePicker 建立一个时间延长(小时/分钟/秒)(因为那里还没有任何好的)。问题是当我更新时间组件中的时间时,我使用 DatePickers选择方法,这是使用 Date 对象以编程方式设置日期的唯一方法。
问题是 Datepickers 内部选择功能不会将不同的小时/分钟/秒视为不同的日期,并且当提供此类方案时,它不会更新其内部工作。

以下是Angular Material Datepicker的选择功能:

MatDatepicker.prototype.select = function (date) {
    var oldValue = this._selected;
    this._selected = date;
    // this will eveluate as false since only hours/minuts/seconds are different and not day/month/year
    if (!this._dateAdapter.sameDate(oldValue, this._selected)) { 
        this._selectedChanged.next(date);
    }
};   

sameDate方法中,他们使用一个名为compareDate的方法,该方法仅按日、月和年检查两个日期:

DateAdapter.prototype.compareDate = function (first, second) {
    return this.getYear(first) - this.getYear(second) ||
        this.getMonth(first) - this.getMonth(second) ||
        this.getDate(first) - this.getDate(second);
};

这意味着select方法不会将新日期发送到 DatePicker 的内部组件和部件。

我正在使用自定义NativeDateAdapter和自定义MatDateFormats但由于上述检查想要发出新的日期,因此需要达到这些机制。

PS
当更新的日期具有不同的日/年/月(包括自定义时间格式以包含时间参数)时,一切正常。

标签: angular-materialangular7angular8

解决方案


我通过使用自定义 NativeDateAdapter 简单地重新实现基类compareDate方法解决了这个问题。

export class AppDateAdapter extends NativeDateAdapter {
    format(date: Date, displayFormat: Object): string {
        // format your dates
    }
    compareDate(first: Date, second: Date) {
       // compare first/current date with second/previous date
       // you can implement your logic here.
       return 1;
    }
}

推荐阅读