Reputation: 11744
I'm using the Moment.js library for some time operations in a project.
I currently use the calendar
function, which returns information like "Today at 6:28 PM" or "last Sunday at 6:42 PM".
I now have a need for second-accurate information, like "Today at 6:28:39 PM" or "last Sunday at 6:42:55 PM". Is there any built-in way to do this in the Moment.js library?
Upvotes: 4
Views: 2129
Reputation: 46589
Moment is highly customizable. In this case you want to format the LT entry, since the calendar object uses that:
moment. locale('en', {
calendar : {
lastDay : '[Yesterday at] LT',
sameDay : '[Today at] LT',
nextDay : '[Tomorrow at] LT',
lastWeek : '[last] dddd [at] LT',
nextWeek : 'dddd [at] LT',
sameElse : 'L'
}
});
Before altering it:
moment().subtract('days', 2).calendar()
"last Wednesday at 3:44 PM"
So now you need to customize the LT:
moment.locale('en', {
longDateFormat : {
LT: "h:mm:ss A", // <----------- add :ss
L: "MM/DD/YYYY",
l: "M/D/YYYY",
LL: "MMMM Do YYYY",
ll: "MMM D YYYY",
LLL: "MMMM Do YYYY LT",
lll: "MMM D YYYY LT",
LLLL: "dddd, MMMM Do YYYY LT",
llll: "ddd, MMM D YYYY LT"
}
});
And now you get seconds in your time:
moment().subtract('days', 2).calendar()
"last Wednesday at 3:41:05 PM"
Upvotes: 4
Reputation: 3685
You can alter Moment's long date formats to include seconds. By default, the calendar
function uses the LT
format, which is initially set to "h:mm a"
(time to minutes plus AM/PM). You can alter the LT
format to include seconds ("h:mm:ss A"
) as follows:
moment.lang('en', {
longDateFormat : {
LT: "h:mm:ss A",
L: "MM/DD/YYYY",
l: "M/D/YYYY",
LL: "MMMM Do YYYY",
ll: "MMM D YYYY",
LLL: "MMMM Do YYYY LT",
lll: "MMM D YYYY LT",
LLLL: "dddd, MMMM Do YYYY LT",
llll: "ddd, MMM D YYYY LT"
}
});
Upvotes: 2