mrrsb mrrsb - 3 months ago 8
Javascript Question

Don't want to display the year only if it is current year ,in moment.js

I have this code to transform date to a readable time format

$('time').each(function (i, e) {

if ($(e).attr("class") == 'mtime') {

var now = moment();
moment.lang('en', {
calendar : {
lastDay : '[Yesterday] LT',
sameDay : 'LT',
nextDay : '[Tomorrow,] LT',
lastWeek : 'ddd LT',
nextWeek : 'ddd LT',
sameElse : 'MMM D[/]YY' //something to do with this?
}

});

var elem = $(e).attr('datetime');
var time = moment($(e).attr('datetime'));
var diff = now.diff(time, 'days');

$(e).html(time.calendar());

}

});


returned output:

<time class="mtime" datetime="2016-02-26 10:31:22" title="2016-02-26 10:31:22">Feb 26/16</time>


The problem is how can I hide the year if current year. And if past year format it to "M/D/YY".

expected output:

- <time>Feb 26</time> <!--// current year -->
- <time>12/25/15</time> <!--// last year -->
- <time>8/1/14</time> <!--// last year -->


Kindly advise guys! TIA

Answer

From version 2.14.0 we can pass callbacks to specific moment context:

sameElse: function() {
  if (this.years() === now.year()) {
    return 'MMM D'
  } else {
    return 'M/D/YY';
  }
}

$('time').each(function(i, e) {
  if ($(e).attr("class") == 'mtime') {
    var now = moment();
    moment.lang('en', {
      calendar: {
        lastDay: '[Yesterday] LT',
        sameDay: 'LT',
        nextDay: '[Tomorrow,] LT',
        lastWeek: 'ddd LT',
        nextWeek: 'ddd LT',
        sameElse: function() {
          if (this.years() === now.year()) {
            return 'MMM D'
          } else {
            return 'M/D/YY';
          }
        }
      }
    });
    var elem = $(e).attr('datetime');
    var time = moment($(e).attr('datetime'));
    var diff = now.diff(time, 'days');
    $(e).html(time.calendar());
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<time class="mtime" datetime="2016-02-26 10:31:22"></time> <br />
<time class="mtime" datetime="2015-12-25 10:31:22"></time> <br />
<time class="mtime" datetime="2014-08-01 10:31:22"></time> <br />