2015-03-25 138 views

回答

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(); 
    } 
}