javascript - Angular 4 日期管道短时间格式,每分钟更新一次

标签 javascript angular date time pipe

我需要一个可用的 Angular 4 数字时钟
尝试使用正常的 javascript 和 setInterval 使其每 60 秒运行一次函数。但字符串插值不会更新属性更改时的时间。

theDate = new Date();
theDay = this.theDate.getDay();
hours = this.theDate.getHours();
minutes = this.theDate.getMinutes();
session = "AM";
ngOnInit() {
    if (this.hours == 0) {
        this.hours = 12;
    }

    if (this.hours > 12) {
        this.hours = this.hours - 12;
        this.session = "PM";
    }
    this.stringHours = (this.hours < 10) ? "0" + this.hours : this.hours;
    this.stringMinutes = (this.minutes < 10) ? "0" + this.minutes : this.minutes;
    this.clock = this.stringHours + ":" + this.stringMinutes + " " + this.session;
    this.refreshClock();
}
refreshClock() {
    setInterval(() => {
        this.hours = this.theDate.getHours();
        this.minutes = this.theDate.getMinutes();
        this.stringHours = (this.hours < 10) ? "0" + this.hours : this.hours;
        this.stringMinutes = (this.minutes < 10) ? "0" + this.minutes : this.minutes;
        this.clock = this.stringHours + ":" + this.stringMinutes + " " + this.session;
        console.log('work');
    }, 1000)

}

所以我尝试了 Angular 日期管道,但它也没有更新时间,只是在刷新应用程序后刷新它。

typescript

theDate = new Date();

HTML

 {{ theDate | date :'shortTime' }}

Angular 日期管:
https://angular.io/api/common/DatePipe

最佳答案

您错过了更新 setInterval() 内的 theDate

refreshClock() {
    setInterval(() => {
        this.hours = this.theDate.getHours();
        this.minutes = this.theDate.getMinutes();
        this.stringHours = (this.hours < 10) ? "0" + this.hours : this.hours;
        this.stringMinutes = (this.minutes < 10) ? "0" + this.minutes : this.minutes;
        this.clock = this.stringHours + ":" + this.stringMinutes + " " + this.session;
        console.log('work');
        // add this line
        this.theDate = newly calculated date
    }, 1000)

}

DEMO

关于javascript - Angular 4 日期管道短时间格式,每分钟更新一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50679150/

相关文章:

javascript - Angular7 运行时编译

.net - 本地化日期格式描述符

javascript - Mocha 测试运行器 - 仅重新运行上一次运行失败的测试的选项

javascript - 显示按钮单击 Angular 2 的详细信息

javascript - 流程图无返回数据

angular - 等待第 3 方 JS 库在 Angular 2 服务中完成初始化的最佳方法?

php - 当日期为 UNIX 时间戳格式时,如何按日期对记录进行分组?

Javascript 日期对象时区问题 - 不同的时区

javascript - _ (lodash) 声明为 peerDependency 时的引用错误

javascript - 数组 is.Array if 和 else 语句