我想以文本形式显示不久前的日期,并且我喜欢 moment.js 格式化程序。我正在使用 php 来回显当前日期,但还没有找到一个好的前段时间格式化程序,因此我想使用 moment.js。
我正在考虑在 html 页面中将 {12345678}
回显为 unix 时间戳,然后在使用 moment.js fromNow()
格式化后使用 jquery 替换每个标记> document.ready 上的函数。
这是一个好的解决方案吗?如果是这样,我如何迭代所有标记,处理日期,然后替换内容?
我已阅读如何使用 replaceWith()
和 replace
,但它们不允许我处理 token 。
这可能是一种遥远的方法,因为可能只是一个简单的 php time-ago 格式化程序助手...
有什么想法吗?
最佳答案
所以....
这是我的解决方案。
JS:
// time formatter
$( "[data-time-format]" ).each(function() {
var el = $( this );
switch(el.attr("data-time-format")) {
case "time-ago":
var timeValue = el.attr("data-time-value")
var strTimeAgo = moment.unix(timeValue).fromNow();
el.text(strTimeAgo);
break;
}
});
HTML:
<span data-time-format="time-ago" data-time-value="{UNIX TIMESTAMP}"></span>
这段Js片段会迭代所有具有“data-time-format”属性的元素,然后使用switch语句进行处理。我正在使用开关,因为我将使用此数据属性进行其他时间戳处理,所以我需要灵活性。
J应该放在document.ready中。
关于javascript - 使用 moment.js 处理 View 中的 php 日期的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32621630/