最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Display time using moment.js only if not 00:00:00 - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 3

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 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.

发布评论

评论列表(0)

  1. 暂无评论