Javascript 使用 moment.js 转换日期格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13737509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:46:49  来源:igfitidea点击:

Use moment.js to convert date format

javascriptjquerymomentjs

提问by Mark Mitchell

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)

我想使用 Javascripy/jQuery 转换以下日期。我的研究似乎指向 moment.js,它看起来很棒,但我似乎无法确定它。(JS 半菜鸟)

<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

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".

如果日期在过去 24 小时内,如果相同的逻辑可以将额外的类应用到 div,那也太棒了,所以我可以稍微改变它们的样式。也许在过去 24 小时内添加一个类而不是日期显示“新”的日期。

Thanks!

谢谢!

回答by Peter Lyons

$(function () {
  $('.date').each(function (index, dateElem) {
    var $dateElem = $(dateElem);
    var formatted = moment($dateElem.text(), 'MM-DD-YYYY').format('MMMM D');
    $dateElem.text(formatted);
   })
 });?

http://jsfiddle.net/x2fDP/

http://jsfiddle.net/x2fDP/

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');

对于第 2 部分,尝试使用new Date().getTime() - textMoment.valueOf()(其中 textMoment 是从 div 的文本创建的解析时刻实例)获取该日期之前的毫秒数,如果该数字低于您的阈值,请使用$dateElem.addClass('new');