如何将UTC字符串日期转为数字,适配ngx-countdown的leftTime配置
问题:Angular子组件中ngx-countdown无法处理UTC字符串日期参数
我调用C# API,返回的类型定义如下:
export interface Auction { reservePrice: number currentHighBid: number auctionEnd: string id: string }
我创建了AuctionListComponent,用*ngFor展示拍卖列表,同时创建子组件TimerComponent实现倒计时功能。父组件向子组件传递UTC格式的字符串日期,但ngx-countdown的leftTime参数需要数字类型,尝试两种输入类型均出现问题:
- 定义
@Input() childTimer: string = '':类型不匹配,无法正常工作 - 定义
@Input() childTimer: any:编译通过,但运行时报错ERROR Error: Unable to convert "Invalid Date" into a date
父组件(AuctionListComponent.html)
<div class="m-3" *ngFor="let auction of auctions"> <p class="card-text"> End Date: {{ auction.auctionEnd | date }} </p> <app-timer [childTimer]="auction.auctionEnd"></app-timer> </div>
子组件(TimerComponent.html)
<p> From the parent: <b>{{ childTimer | date : 'MM d, y, h:mm:ss a' }}</b> UTC: <b>{{ childTimer }}</b> </p> <p>ngx-countdown Counter</p> <countdown [config]="config"> </countdown>
子组件(TimerComponent.ts)
import { Component, Input } from '@angular/core'; import { CountdownConfig, CountdownEvent } from 'ngx-countdown'; @Component({ selector: 'app-timer', templateUrl: './timer.component.html', styleUrl: './timer.component.scss' }) export class TimerComponent { @Input() childTimer: string = ''; //类型错误,无法工作 @Input() childTimer: any; //编译通过但报错:ERROR Error: Unable to convert "Invalid Date" into a date config: CountdownConfig = { leftTime: this.childTimer, format: 'd:H:M:ss'}; }
解决方案
核心是将UTC字符串转换为ngx-countdown需要的剩余秒数,同时确保日期解析有效。
步骤1:监听输入变化并计算剩余时间
由于@Input属性在组件初始化后才传入,不能直接在类初始化时赋值config,需用ngOnChanges钩子监听输入变化,动态计算剩余时间:
修改TimerComponent.ts如下:
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; import { CountdownConfig } from 'ngx-countdown'; @Component({ selector: 'app-timer', templateUrl: './timer.component.html', styleUrl: './timer.component.scss' }) export class TimerComponent implements OnChanges { @Input() childTimer!: string; config: CountdownConfig = { format: 'd:H:M:ss' }; ngOnChanges(changes: SimpleChanges): void { if (changes['childTimer'] && this.childTimer) { const endDate = new Date(this.childTimer); // 校验日期是否有效,避免Invalid Date错误 if (!isNaN(endDate.getTime())) { const now = new Date(); // 计算剩余秒数,取最大值0避免倒计时为负数 const leftTime = Math.max(0, endDate.getTime() - now.getTime()) / 1000; this.config = { ...this.config, leftTime }; } } } }
步骤2:兼容非标准UTC格式(可选)
如果API返回的UTC格式不被Date对象兼容(比如"2024-12-31 23:59:59"),可手动转换为标准格式:
// 示例:将空格替换为T并添加Z后缀 const formattedDate = this.childTimer.replace(' ', 'T') + 'Z'; const endDate = new Date(formattedDate);
内容的提问来源于stack exchange,提问作者whisk
相关产品推荐
相关产品推荐

