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

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

问题描述

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

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表示一天前,年份(1y),星期(1w)等也是如此.

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

}

此处是显示到前端的html HTML:

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?

推荐答案

我同意Moment是处理JavaScript中日期的一种方式.

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.

我更新了StackBlitz,增加了输出天,年等"的功能.非常简单,您只需利用.humanize()功能

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

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

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/zh/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天全站免登陆