gpt4 book ai didi

javascript - 如何在 Angular 6 中格式化日期?

转载 作者:搜寻专家 更新时间:2023-10-30 21:34:57 25 4
gpt4 key购买 nike

我有一个功能可以显示用户输入的实时日期,现在当用户输入时我在前端显示了这样的东西[日期]:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com