作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有一个功能可以显示用户输入的实时日期,现在当用户输入时我在前端显示了这样的东西[日期]:
28.10.2018 10:09
如果是过去的几天、过去的一周、过去的一年等,我想改变日期
因此,如果昨天输入了内容,我想显示如下内容:
1d
表示一天前,同样适用于年 (1y
) 、周 (1w
) 等
到目前为止,这是我尝试过的:
这是抓取日期及其输入文本的函数
this.activeRouter.params.subscribe((params) => {
let id = params['id'];
this.userService.getComments(id)
.pipe(
map(data => data.sort((a, b) => new Date(b.localTime).getTime() - new Date(a.localTime).getTime()))
)
.subscribe(data => this.comments = data);
});
他这里是向服务器添加文本输入和日期的功能
addComments(task_id) {
const formData = this.addForm.value;
formData.task_id = task_id;
this.userService.addComments(formData)
.subscribe(data => {
this.comments.push(this.addForm.value);
this.addForm.reset();
});
const date = new Date();
const d = date.getUTCDate();
const day = (d < 10) ? '0' + d : d;
const m = date.getUTCMonth() + 1;
const month = (m < 10) ? '0' + m : m;
const year = date.getUTCFullYear();
const h = date.getUTCHours();
const hour = (h < 10) ? '0' + h : h;
const mi = date.getUTCMinutes();
const minute = (mi < 10) ? '0' + mi : mi;
const sc = date.getUTCSeconds();
const second = (sc < 10) ? '0' + sc : sc;
const loctime = `${year}-${month}-${day}T${hour}`;
this. addForm.get('localTime').setValue(loctime);
}
这是显示给前端的htmlHTML:
<div class="comments_details">
<h1>Mike Ross</h1>
<span class="days">{{comment.localTime | date:'dd.MM.yyyy H:mm'}}</span>
</div>
这里是抓取数据并添加到服务器的服务函数
addComments(comments: Comment) {
comments.localTime = new Date();
return this.http.post(this.commentsUrl, comments);
}
getComments(id: number) {
return this.http.get<Comment[]>(this.commentsUrl);
}
我需要在我的代码中更改什么才能获得我想要的格式?
最佳答案
我认为你不应该在 Angular 中使用力矩。它不是可摇树的,会使你的包变得很大。你应该看看 date-fns 或 date.js。
关于javascript - 如何在 Angular 6 中格式化日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53033868/
我是一名优秀的程序员,十分优秀!