B
B
ByJumping2022-02-01 12:23:04
JavaScript
ByJumping, 2022-02-01 12:23:04

How to output date in specified format with moment js library?

You need to display the date in a convenient format. The date when the person left the comment arrives from the backend. It is necessary to output in the following format -
1. If the input time is > 6 months from the current one: output 01/12/2020 - without hours, minutes and seconds
2. If the input time is > a month and less than 6 months from the current one: output N months ago
3. If the input time > 24 hours and less than a month from the current time: output N days ago
4. If input time < 24 hours from current time: output N hours ago
5. If input time < 60 minutes from current time: output N minutes ago
6. If input time < 60 seconds from the current one: output N seconds

ago

export default class DateUtils {
  static getHumanDate(date) {
    try {
      const month = moment(date).format('MM'); // месяц входящей даты
      const currentMonth = moment().format('MM'); // текущий месяц
      const currentYear = moment().format('YYYY'); // текущий год

      if (
        currentYear - moment(date).format('YYYY') < 1 &&
        currentMonth - month < 6
      ) {
        return moment(date, 'YYYYMMDD').fromNow();
      }

      return moment(date).format('DD.MM.YYYY');
    } catch (e) {
      console.log(e); // todo: notify?
    }

    return null;
  }
}

For tests in the component, I pass the date:

calculateDate(date) {
      console.log(DateUtils.getHumanDate('2022-02-01'));
    },

Now it is displayed correctly only if the input time is > 6 months from the current time and if the input time is > 24 hours and less than a month. How to add the rest of the conditions I do not understand.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JavaDev, 2022-02-01
@ByJumping

Well, for starters, before using any tool, I advise you to read its documentation. After all, it is in the documentation that it is described how this tool works.
And now how to do it.
moment.js has methods like .add() and .subtract() that allow you to add and subtract time.
There are also .isBefore() , .isAfter() , .isBetween() methods that compare dates.
Knowing these methods, you can start implementing

const currentDate = moment(); // текущая дата
// далее к дате комментария добавляем 6 месяцев и сравниваем с текущей датой
const isAfterSixMonth = moment(date).add(6, 'months').isAfter(currentDate);
if(isAfterSixMonth) { // если дата комеентария + 6 месяцев > текущая дата
  // выводим нужный формат
}

This is the first point, the rest are done by analogy.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question