Balakumar B
Balakumar B

Reputation: 790

How to Check Given Date is This week or Last Week in JavaScript

I need to check the given date is 'Today', 'Yesterday', 'This Week', 'Last Week', 'This Month', 'Last Month', 'Sep', 'Aug', 'Jul', .... '2019', '2018', etc.... in JavaScript.

and I am using Moment js for showing Datetime

moment.tz(message.receivedDateTime, 'America/Denver').format("hh:mm A")

We have an array of the message with content and date of that messages has received, so we need to Check Date and showing list of messages like the following format in JavaScript.

Today
    Message 1 
    Message 2
Yesterday
    Message 3
    Message 4
This Week
    Message 5
Last Week
    Message 6
    Message 7

etc...

Upvotes: 0

Views: 820

Answers (1)

ricardo-dlc
ricardo-dlc

Reputation: 486

Maybe too late, but if you don't have a way this could be helpful to your own. You can support on calendar() which says:

Calendar time displays time relative to a given referenceDay (defaults to the start of today). [...] Note: From version 2.25.0 you can only pass a formats argument, it could be an object of strings and functions.

The defaults for this are:

moment().calendar({
    sameDay: '[Today]',
    nextDay: '[Tomorrow]',
    nextWeek: 'dddd',
    lastDay: '[Yesterday]',
    lastWeek: '[Last] dddd',
    sameElse: 'DD/MM/YYYY'
});

sameElse is used as the format when the moment is more than a week away from the referenceDay.

And difference() to get the difference in milliseconds, or in another unit of measurement.

So for cases less than a week (or 7 days) you can use lastWeek and for those cases more than a week use sameElse, something like this:

function calendarDate(date) {
  return moment(date).calendar({
    sameElse: function (now) {
      const from = moment(this);
      now = moment(now);
      const dayDiff = now.diff(from, 'days');
      if (dayDiff >= 7 && dayDiff <= 14) {
        return '[Last week]';
      } else {
        const monthDiff = now.diff(from, 'months', true);
        if (monthDiff === 0) {
          return '[This month]';
        }
        if (monthDiff > 0 && monthDiff <= 1) {
          return '[Last Month]';
        }
        if (monthDiff > 1) {
          if (Number(from.format('YYYY')) - Number(now.format('YYYY')) < 0) {
            return `[${from.format('YYYY')}]`;
          }
          return `[${from.format('MMMM')}]`;
        }
      }
      return '[More than a week]';
    },
  });
}

console.log(calendarDate('2020-11-01'));
console.log(calendarDate('2020-10-23'));
console.log(calendarDate('2020-09-30'));
<script src="https://momentjs.com/downloads/moment.js"></script>

Also you can return you message directly from the function instead of the "time ago" string.

Remember that this is just an example and you can adjust the ranges according to your needs.

Upvotes: 1

Related Questions