所以,这是关于使用具有日期/时间属性的API。内容应该每3小时更改一次,通过比较当前用户的日期/时间与API的时间,并在单独的数组中分配过去和即将到来的时间,以显示在页面的其他部分。我设法将过去和即将到来的日期分配到各自的数组中。我需要比较日期并分配"当前数据"。如果用户的日期/时间等于或小于3小时,则在属性中显示整个3小时的持续时间。
this.dataService.getData().subscribe((data:any[])=>{
const now = new Date('2021-02-14 09:00:00');
for (const item of data) {
const apiDate = new Date(item.dateTime);
if(now.getTime() > apiDate.getTime()){
this.future.push('future dates')
} else if(now.getTime() < apiDate.getTime()){
this.past.push('past dates')
}else if(now.getTime() == apiDate.getTime()){
//in real time, they'll only be equal for one second
this.current = 'Show NOW'
}
}
这是API/Json数据返回的结构
[ { "number": 10, "dateTime": "2021-02-14 00:00:00" }, { "number": 20, "dateTime": "2021-02-14 03:00:00" }, { "number": 30, "dateTime": "2021-02-14 06:00:00" }, { "number": 40, "dateTime": "2021-02-14 09:00:00" }, { "number": 50, "dateTime": "2021-02-14 12:00:00" }]
一个更好的方法甚至会更好。
感谢如果你想显示时间范围内,那么你可以创建一个对象与你的时间界限:
getTimeInterval = () => {
const from = new Date();
const to = new Date(from);
to.setHours(to.getHours() + 3)
return { from, to };
}
然后检查日期from
和to
的边界:
this.dataService.getData().subscribe((data:any[])=>{
const dateRange = this.getTimeInterval();
for (const item of data) {
const apiDate = new Date(item.dateTime);
if (dateRange.from.getTime() > apiDate.getTime()
&& dateRange.to.getTime() > apiDate.getTime())
{
this.future.push('future dates');
}
else if(dateRange.from.getTime() < apiDate.getTime())
{
this.past.push('past dates')
}
else if (dateRange.from.getTime() >= apiDate.getTime()
&& dateRange.to.getTime() <= apiDate.getTime())
{
this.current = 'Show NOW'
}
}