Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment.js - display either date OR time

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?

like image 449
Fatal Avatar asked Apr 24 '12 03:04

Fatal


People also ask

How do you find moment with time and date?

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.

How do you show time using a moment?

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.

Is moment JS being deprecated?

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.


2 Answers

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();
}
like image 114
Femi Avatar answered Oct 13 '22 17:10

Femi


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);
}
like image 28
timrwood Avatar answered Oct 13 '22 18:10

timrwood