javascript - Is there a way to replace today date with hours?
问题描述
I'm building this app that get articles from a DB and 1 of the fields is the date which right now is in format '2019-06-13T18:03:58.000Z' and basically what I need to do is check if this is today's date return onyl the hours and am/pm so for this example is today so return 18:03pm, if the date is the same as yesterday's then return 'yesterday'and if the date is other than those then return 'Month, day'
I've tried creating Date objects and then compare but it didn't work
I have this code for the html:
<div class='date-container'>
{{renderDate(data.created_at)}}
</div>
and in the component.ts file:
public renderDate(date) {
const fecha = new Date(date);
const today = new Date();
const yesterday = today.getDate()-1;
let fecha_r = '';
if(fecha.getTime() == today.getTime()){
fecha_r = 'today';
}
return fecha_r;
}
I need to return the converted date in that function so my html code prints the correct formated date how can I do this?
解决方案
I'd recommend making use of a custom pipe for you date value output. Angular isn't able to cache function results, so they get called at every change detection cycle. Pipes only get called when the input values change. I'd think something like this would do the trick:
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({name: 'customDatePipe'})
export class CustomDatePipe implements PipeTransform {
transform(value: Date): string {
const datePipe = new DatePipe('en-US');
const today = new Date();
if (today.getDate() === value.getDate() && today.getMonth() === value.getMonth() && today.getFullYear() === value.getFullYear()) {
return datePipe.transform(value, 'hh:mmaa');
} else {
return datePipe.transform(value, 'MMM, d');
}
}
}
This is making use of the built in Date Pipe to do the final string transform. You'll just have to add the pipe in the declarations of your module and then you can use it like {{ data.createdAt | customDatePipe}}
.
推荐阅读
- batch-file - 从批处理文件运行时无法从 Octave 脚本创建 Excel 文件
- python - python3中的最大除数
- googlebot - 我会阻止一些谷歌相关服务的IP吗?
- python - 品牌名称:AttributeError:“NoneType”对象没有属性“文本”
- java - 为什么使用不同的计算机/屏幕调整秋千组件的大小?
- angular - 提交时无法更改输入值
- r - 在 R 中运行游侠模型时输入变异错误
- r - 在条形图中为分类变量添加计数百分比;ggplots
- pip - 尝试 conda-build graphviz pypi 包时出现 HTTP 错误
- python - 在所有正在运行的 gunicorn 工作者中执行代码