On a page that I'm building, there is a requirement to either display the date (eg: 15 Aug) or, if the date is today, just display a time, eg: 10pm.
What would be the best way of coaxing that behaviour out of moment.js?
The format i'd like for a date is 'd MMM' and the format for time would be 'hA' (if minutes are 0) or 'h:mmA' (if minutes are not 0).
Any ideas on how to approach this? It looks like the calendar() function might be able to support something like that?
js parsing date and time. We can parse a string representation of date and time by passing the date and time format to the moment function. const moment = require('moment'); let day = "03/04/2008"; let parsed = moment(day, "DD/MM/YYYY"); console.
To get the current date and time, just call javascript moment() with no parameters like so: var now = moment(); This is essentially the same as calling moment(new Date()) . Unless you specify a time zone offset, parsing a string will create a date in the current time zone.
MomentJs recently announced that the library is now deprecated. This is a big deal for the javascript community who actively downloads moment almost 15 million times a week. With that I began a journey during a Hackathon to replace moment in a core library at my company.
You want to use moment.calendar: set everything except sameDay
to d MMMM and sameDay
to h:mmA. You can't do finer grain than that.
function timeTodayDateElse(date){
moment.lang('en', {
'calendar' : {
'lastDay' : 'D MMMM',
'sameDay' : 'h:mmA',
'nextDay' : 'D MMMM',
'lastWeek' : 'D MMMM',
'nextWeek' : 'D MMMM',
'sameElse' : 'D MMMM'
}
});
return moment(date).calendar();
}
You could write a micro plugin to do this yourself.
moment.fn.formatTimeToday = function () {
var now = moment(),
format = "d MMM";
if (this.date() === now.date() &&
Math.abs(this.diff(now)) < 86400000) {
// same day of month and less than 24 hours difference
if (this.minutes() === 0) {
format = "hA";
} else {
format = "h:mmA";
}
}
return this.format(format);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With