Reputation: 573
I'm using moment to get time ago, but for things that happened 1 hour ago, it puts it like this: 'am hour ago', is it possible to get '1 hour ago'? Same thing for months, 'a month ago' => '1 month ago'
Upvotes: 0
Views: 4702
Reputation: 176
You can configure moment to display relative times in any format you desire. For example:
moment.updateLocale('en', {
relativeTime : {
future: "in %s",
past: "%s ago",
s : 'a few seconds',
ss : '%d seconds',
m: "a minute",
mm: "%d minutes",
h: "1 hour ago", //this is the setting that you need to change
hh: "%d hours",
d: "a day",
dd: "%d days",
w: "a week",
ww: "%d weeks",
M: "1 month ago", //change this for month
MM: "%d months",
y: "a year",
yy: "%d years"
}
});
After this change has been made the moment library can be used as usual.
Following are some examples:
moment('2021-07-23 14:00:00').fromNow();
If you have the date coming in a different format than expected then you also need to provide the format in which you are getting it. Not doing so will return 'Invalid date'.
moment('21/07/2021',"DD/MM/YYYY").fromNow();
You can also specify multiple formats:
moment('21-07-2021', ['DD/MM/YYYY', 'YYYY/MM/DD']).fromNow();
You can always check whether you got a valid date or not. This helps put some checks in place or can be helpful when debugging code:
moment('abc', ['MM/DD/YYYY', 'YYYY/MM/DD']).isValid() //false
For more information see the docs here: https://momentjs.com/docs/#/customization/relative-time/
Upvotes: 3