如何通过angular2-moment将时间显示为1 mins ago?
amTimeAgo to Show "1 mins ago" in angular2-moment To get the amTimeAgo pipe to display "1 mins ago" instead of the default "1 minute ago", you can customize Moment.js's relative time formatting directly—since angular2-moment relies on Moment.js under the hood. Here's how to do it step by step:
Step 1: Configure Moment.js Locale in Your App
In your Angular project (most commonly in app.module.ts), import Moment.js and update the English locale's relative time rules to match your desired output. This ensures the change applies globally across your app.
import { NgModule, OnInit } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { MomentModule } from 'angular2-moment'; // Make sure you've imported this module import * as moment from 'moment'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, MomentModule], bootstrap: [AppComponent] }) export class AppModule implements OnInit { ngOnInit(): void { // Override relative time strings for the English locale moment.updateLocale('en', { relativeTime: { m: '1 mins ago', // Customize singular minute text mm: '%d mins ago', // Customize plural minute text // Keep other formats default, or tweak them if needed s: 'a few seconds ago', h: '1 hour ago', hh: '%d hours ago', d: '1 day ago', dd: '%d days ago', M: '1 month ago', MM: '%d months ago', y: '1 year ago', yy: '%d years ago' } }); } }
Step 2: Verify Your Template Usage
Double-check your template code (note the date string should be wrapped in quotes to avoid syntax errors):
<div>{{'2018-04-16T05:56:45.200Z' | amTimeAgo}}</div>
Key Details
The amTimeAgo pipe uses Moment.js's fromNow() method behind the scenes. By updating the locale configuration, you're overriding Moment's default relative time strings:
mtargets the singular case (1 minute)mmtargets the plural case (2+ minutes)
If you only need to modify minute-related text and leave other formats as default, you can simplify the configuration to just:
moment.updateLocale('en', { relativeTime: { m: '1 mins ago', mm: '%d mins ago' } });
Moment will merge your customizations with its default locale settings automatically.
内容的提问来源于stack exchange,提问作者Aditya

