简体   繁体   English

使用moment.js转换日期格式

[英]Use moment.js to convert date format

I would like to convert the following dates using Javascripy/jQuery. 我想使用Javascripy / jQuery转换以下日期。 My research seems to point to moment.js which looks awesome but I can't seem to nail it. 我的研究似乎指向了看起来很棒的moment.js,但我似乎无法指出它。 (JS semi-noob) (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. 如果日期在过去的24小时内,如果相同的逻辑可以将另一个类应用于div,那么它也会很棒,所以我可以将它们设置得有点不同。 Maybe have the dates within the last 24 hours add a class and instead of a date display "new". 也许有过去24小时内的日期添加一个类而不是日期显示“新”。

Thanks! 谢谢!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM