Use moment.js to convert date format

39,641
$(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/

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

Share:
39,641
Mark Mitchell
Author by

Mark Mitchell

Updated on July 19, 2022

Comments

  • Mark Mitchell
    Mark Mitchell almost 2 years

    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
    

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

    Thanks!

  • Mark Mitchell
    Mark Mitchell over 11 years
    Awesome. IS there any way to add the class to the div and text "new" instead of displaying the date if the date is within the last 24 hours? The reformatting rocked. (IT's the latter part of my question under the code above.)
  • SrAxi
    SrAxi almost 10 years
    To add a class try .addClass(). You can find the propper use of it here: api.jquery.com/addclass. If this helped you don't forget to upvote! ;) Good luck mate!