使用moment.js转换日期格式 [英] Use moment.js to convert date format
问题描述
我想使用Javascripy / jQuery转换以下日期。我的研究似乎指向了看起来很棒的moment.js,但我似乎无法指出它。 (JS半正午)
I would like to convert the following dates using Javascripy/jQuery. My research seems to point to moment.js which looks awesome but I can't seem to nail it. (JS semi-noob)
<div class="date">01-06-2012</div> convert to display January 6
<div class="date">05-14-2012</div> convert to display May 14
<div class="date">06-16-2012</div> to display June 16
如果相同的逻辑可以向div应用额外的类,那将是很棒的如果日期在过去的24小时内,那么我可以将它们设计得有点不同。也许有过去24小时内的日期添加一个类而不是日期显示新。
Also it would be awesome if the same logic can apply an additional class to the div if the date is within the last 24 hours, so I can style those a bit differently. Maybe have the dates within the last 24 hours add a class and instead of a date display "new".
谢谢!
推荐答案
$(function () {
$('.date').each(function (index, dateElem) {
var $dateElem = $(dateElem);
var formatted = moment($dateElem.text(), 'MM-DD-YYYY').format('MMMM D');
$dateElem.text(formatted);
})
});
第2部分,尝试使用 new Date()。getTime() - textMoment.valueOf()
(其中textMoment是从div文本创建的解析时刻实例)以获得毫秒数之前该日期是,如果该数字低于您的阈值,请使用 $ dateElem.addClass('new');
For part 2, try using new Date().getTime() - textMoment.valueOf()
(where textMoment is the parsed moment instance created from the div's text) to obtain the number of milliseconds ago that date was and if that number is below your threshold, use $dateElem.addClass('new');
这篇关于使用moment.js转换日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!