如何在没有时间的情况下获得ReferenceTime

时间:2015-03-25 08:10:49

标签: momentjs

MomentJS有选项" referanceTime" - http://momentjs.com/docs/#/displaying/calendar-time/,它显示日期时间Last Monday 2:30 AM 问题是当我没有时间约会时 - 它会显示Last Monday 0:00 AM - 当日期没有得到它时如何摆脱时间?

2 个答案:

答案 0 :(得分:1)

与我的回答here非常相似,但略高一些。

我认为自定义日历时间的唯一方法是使用custom locale。在您的情况下,您需要使用自定义函数。

这是一个有点复杂但完整的方法:

// Factory-type function that returns a function.
// Used to set argument (fstr) without using `bind` (since bind changes `this`)
var stripZeroTime = function (fstr) {
    return function () {
        if (this.format("H:mm:ss") === "0:00:00") { // if midnight
            return fstr.replace("LT", "") //remove time
                       .replace("at", "") //remove at
                       .replace(/\s+/g, ' ').trim(); //strip extra spaces
        }
        return fstr;
    }
}
moment.locale('en-cust', {
    calendar: {
        lastDay: stripZeroTime('[Yesterday at] LT'), // Default format strings
        sameDay: stripZeroTime('[Today at] LT'),
        nextDay: stripZeroTime('[Tomorrow at] LT'),
        lastWeek: stripZeroTime('[last] dddd [at] LT'),
        nextWeek: stripZeroTime('dddd [at] LT'),
        sameElse: stripZeroTime('L')
    }
});

Demo with test cases

更简单的方法是在午夜时分剥离0:00:00

function stripMidnight(m){
    if(m.format("H:mm:ss") === "0:00:00"){
        return m.calendar().replace("0:00:00","");
    }else{
        return m.calendar();
    }
}

答案 1 :(得分:0)

从2.10.5开始我们可以通过调用(calendar函数的第二个参数)来定义我们自己的渲染引擎 - http://momentjs.com/docs/#/displaying/calendar-time/

但是现在我们只能使用不起作用的字符串来定义模式