Skip to content
Advertisement

Don’t display time if midnight using Moment.js

How do I use http://momentjs.com/docs/ to only display the time if it is not midnight? For instance, please look at the first example below.

console.log(moment('2016-01-28 00:00:00').format('MM/DD/YYYY h:mm:ss A'));
// Desire 01/28/2016, Get 01/28/2016 12:00:00 AM

console.log(moment('2016-01-28 05:03:50').format('MM/DD/YYYY h:mm:ss A'));
// Works correctly.  Desire 01/28/2016 5:03:50 AM, Get 01/28/2016 5:03:50 AM

A possible non-elegant solution would be to use JavaScript to check if the datetime trails with 00:00:00, and if so, provide a format string of ‘MM/DD/YYYY’ instead of ‘MM/DD/YYYY h:mm:ss A’, but I expect there is a more proper way to do so.

Advertisement

Answer

There are many ways. Here’s one way (concise enough for most purposes):

var dt = moment('2016-01-28 00:00:00');
console.log(dt.hours() === 0 && dt.minutes() === 0 && dt.seconds()=== 0 ? dt.format('MM/DD/YYYY'): 
       dt.format('MM/DD/YYYY h:mm:ss A'));
Advertisement