我有这个示例代码(需要使用.js库)来格式化日期。之前从未使用过部分功能,所以不太确定如何使用它。怎么叫他们?这是实用程序库代码:
define(function() {
'use strict';
function _formatDate(justNowText, todayFormat, thisWeekFormat, thisYearFormat, veryOldFormat, date) {
if (!date) { return ""; }
var formattedMoment = moment(date);
var now = moment();
if (now.diff(formattedMoment, "minutes") < 15) {
return justNowText || "Just now";
}
var today = now.startOf('day');
var dateFormat;
if (today <= formattedMoment) {
dateFormat = todayFormat;
} else if (now.diff(formattedMoment, "days") < 7) {
dateFormat = thisWeekFormat;
} else if (formattedMoment.year() >= now.year()) {
dateFormat = thisYearFormat;
} else {
dateFormat = veryOldFormat;
}
return formattedMoment.format(dateFormat);
}
function asShortTimeStampFilter(gettext) {
return _.partial(_formatDate,
gettext("Just now"),
"h:mm A",
"ddd",
"MMM D",
"M/D/YY"
);
}
function asMediumTimeStampFilter(gettext) {
return _.partial(_formatDate,
gettext("Just now"),
"[" + gettext("Today at") + "] h:mm a",
"ddd h:mm a",_formatDate
"MMM D h:mm a",
"M/D/YYYY h:mm a"
);
}
function asDateTimeFormatFilter(gettext) {
return function(date, format) {
if (!date) { return; }
return moment(date).format(format);
};
}
return {
asShortTimeStamp: ['gettext', asShortTimeStampFilter],
asMediumTimeStamp: ['gettext', asMediumTimeStampFilter],
asDateTimeFormat: ['gettext', asDateTimeFormatFilter]
};
});
答案 0 :(得分:3)
Partial application意味着您只传递第一个参数以获取函数,然后您可以使用最终参数调用(多次)。
在你的情况下,库需要一个文本getter函数(例如用于本地化),并返回你传递日期的实际格式化函数。
function id(x) { return x } // just echo the input
var shortTimeStamp = library.asShortTimeStamp[1](id);
console.log(shortTimeStamp(Date.now()))
console.log(shortTimeStamp(Date.now() - 30000)) // 30s ago
console.log(shortTimeStamp(Date.now() - 720000)) // 2h ago
var mediumGermanTimeStamp = library.asMediumTimeStamp[1](function(t) {
return {"Just now":"Grad vorhin", "Today at":"Heut um"}[t];
});
console.log(mediumGermanTimeStamp(Date.now()))
console.log(mediumGermanTimeStamp(Date.now() - 30000)) // 30s ago
console.log(mediumGermanTimeStamp(Date.now() - 720000)) // 2h ago