如何在 Angular 6 中格式化日期? [英] How to format dates in Angular 6?

查看:61
本文介绍了如何在 Angular 6 中格式化日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能可以显示用户输入的实时日期,现在当用户输入时,我在前端显示了类似的内容[日期]:

28.10.2018 10:09

如果日期是过去几天、过去一周、过去一年等,我想更改日期

所以如果昨天输入了输入,我想显示如下内容:

1d 表示一天前,同样适用于一年 (1y) ,一周 (1w) 等

这是我迄今为止尝试过的:

这里是获取日期和输入文本的函数

 this.activeRouter.params.subscribe((params) => {让 id = params['id'];this.userService.getComments(id).管道(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).订阅(数据=> {this.comments.push(this.addForm.value);this.addForm.reset();});const date = new Date();const d = date.getUTCDate();const 天 = (d <10) ?'0' + d : d;const m = date.getUTCMonth() + 1;const 月份 = (m <10) ?'0' + 米:米;const year = date.getUTCFullYear();const h = date.getUTCHours();const 小时 = (h <10) ?'0' + h : h;const mi = date.getUTCMinutes();const 分钟 = (mi <10) ?'0' + 米:米;const sc = date.getUTCSeconds();const second = (sc <10) ?'0' + sc : sc;const loctime = `${year}-${month}-${day}T${hour}`;这个.addForm.get('localTime').setValue(loctime);}

这是显示到前端的htmlHTML:

<h1>迈克·罗斯</h1><span class="days">{{comment.localTime |日期:'dd.MM.yyyy H:mm'}}</span>

这里是抓取和添加数据到服务器的服务函数

 addComments(comments: Comment) {评论.localTime = 新日期();返回 this.http.post(this.commentsUrl, comments);}getComments(id: number) {返回 this.http.get(this.commentsUrl);}

我需要在代码中更改什么才能获得我想要的格式?

解决方案

我同意 Moment 是在 JavaScript 中处理日期的方法.

我这里有几个简单的角度示例:

https://stackblitz.com/edit/angular-moment-example

如果您需要我添加任何特定于该示例的内容,我很乐意这样做.

编辑

我更新了 StackBlitz 的一项功能,可以输出天数、年数等".很简单,你可以利用.humanize()函数

this.humanized = moment.duration(moment().diff(this.startDate)).humanize();

这里没有硬编码.我添加了更多示例,希望它开始有意义.

this.humanized = moment.duration(moment().diff(this.startDate)).humanize();this.humanizedNow = moment.duration(moment().diff(moment())).humanize();//如果你需要强制到天数this.daysFrom2017 = this.currentDate.diff(moment('1/1/2017'), 'days');//如果你需要强制到周数this.weeks = moment().diff(this.startDate, 'week');

您可以强制使用它或仅使用 humanize() 方法,我相信这是您想要的,如果您需要覆盖默认值以更新人性化的单词,您甚至可以设置阈值.

https://momentjscom.readthedocs.io/en/latest/moment/08-durations/03-humanize/

但是,看起来还没有支持自动转换为周,但看起来很快就会出现,这是将添加该功能的更新/拉取请求:

https://github.com/moment/moment/pull/4570/files

但它目前支持除几周外的所有内容

I have a function which displays real time dates from entered input by user, right now when user enter the input I have something like this in front end displayed [date]:

28.10.2018 10:09

I would like the date to change if its past days , past week, past year etc

so if input was entered yesterday I would like to display something like this:

1d meaning one day ago , the same goes for year (1y) , for week (1w) etc.

Here is what I have tried so far:

Here is the function for grabing the date and its input text

 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);
        });

And he here is the function add text input and date to the server

     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);

}

Here is the html for displaying to the fron end HTML:

<div class="comments_details">
              <h1>Mike Ross</h1>
              <span class="days">{{comment.localTime | date:'dd.MM.yyyy H:mm'}}</span>
            </div>

Here is service function for grabing and adding data to the server

  addComments(comments: Comment) {
    comments.localTime = new Date();
    return this.http.post(this.commentsUrl, comments);
  }
  getComments(id: number) {
    return this.http.get<Comment[]>(this.commentsUrl);
  }

What do I need to change in my code to get the format I want?

解决方案

I agree that Moment is the way to go for dealing with dates in JavaScript.

I have a couple simple angular examples here:

https://stackblitz.com/edit/angular-moment-example

If you need me to add anything specific to that example I would be happy to do so.

EDIT

I updated the StackBlitz with a feature to output "Days, Years, etc". It's very easy, you can just take advantage of the .humanize() function

this.humanized = moment.duration(moment().diff(this.startDate)).humanize();

Nothing is hardcoded here.. I've added more examples so hopefully it starts to make sense.

this.humanized = moment.duration(moment().diff(this.startDate)).humanize();
this.humanizedNow = moment.duration(moment().diff(moment())).humanize();

// if you need to force to number of days
this.daysFrom2017 = this.currentDate.diff(moment('1/1/2017'), 'days');

// if you need to force to number of weeks
this.weeks = moment().diff(this.startDate, 'week');

You can force it or just use the humanize() method, which I believe is what you want, you can even set the thresholds if you need to override the defaults for it to update the humanized words.

https://momentjscom.readthedocs.io/en/latest/moment/08-durations/03-humanize/

It does however, look like there is not yet support for automatically doing a conversion to weeks, BUT it looks like it will be there very soon, here is the update/Pull Request that will add that feature:

https://github.com/moment/moment/pull/4570/files

But it currently supports everything but weeks

这篇关于如何在 Angular 6 中格式化日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆