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"));
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"));
Share
Improve this question
asked Nov 2, 2014 at 13:53
user1032531user1032531
26.4k75 gold badges245 silver badges416 bronze badges
2 Answers
Reset to default 3you 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 pare the ticks from start of day to the input time, if both are same, it means the time is zero.
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 {
// plete format
result = date.format('DD/MM/YYYY, h:mm:ss a'); // or whatever it is
}
Documentation for getters/setters use.