Reputation: 26281
How do I display the time using moment.js only if not 00:00:00? The following works, however, seems like a bit of a kludge. Thanks
function convertDate(d) {
var l=d.length;
var f='DD/MM/YYYY'+((l==19 && d.substr(l - 8)=='00:00:00' )?'':', h:mm:ss a');
return moment(d).format(f);
}
console.log(convertDate("2014-11-02 02:04:05"));
console.log(convertDate("2014-11-02 00:00:00"));
Upvotes: 1
Views: 3973
Reputation: 18055
you can use below function to get the format
var getDate = function(d)
{
var format = "DD/MM/YYYY h:mm:ss a";
if(moment(d).startOf('day').valueOf() === moment(d).valueOf())
{
format = "DD/MM/YYYY"
}
return moment(d).format(format);
}
console.log(getDate("2014-11-02 02:04:05"));
console.log(getDate("2014-11-02 00:00:00"));
it compare the ticks from start of day to the input time, if both are same, it means the time is zero.
Upvotes: 3
Reputation: 1922
You could parse the date with moment and then use different formats according to hours/minutes/seconds values.
var date = moment(d);
var result;
if (date.hours() == 0 && date.minutes() == 0 && date.seconds() == 0) {
// format without hours/minutes/seconds
result = date.format('DD/MM/YYYY');
}
else {
// complete format
result = date.format('DD/MM/YYYY, h:mm:ss a'); // or whatever it is
}
Documentation for getters/setters use.
Upvotes: 3