0

I'm trying to count the days from current date to a certain date, and i'm using momentJs to do it, the problem is that it's giving me NaN result, maybe because of the date formatting! I'm fetching the end date from an api, and it's in this format "DD MM YYYY" "16/12/2023" but in moment I don't know how it's formatted, some help would be appreciated.

The code i'm using

const start = moment();
  const end = moment(post.validTill);
  const diff = end.diff(start, "days");

I just want to get the days from current date till the end date !

GrafiCode
  • 3,307
  • 3
  • 26
  • 31
sultan.h
  • 331
  • 1
  • 4
  • 16

1 Answers1

0

You can calculate the duration and request the value in days.

const
  diffInDays = (start, end) => moment.duration(end.diff(start)).asDays(),
  dateFormat = 'DD MM YYYY',
  nextWeek   = moment().add(1, 'weeks').format(dateFormat),
  post       = { validTill: nextWeek },
  diff       = diffInDays(moment(), moment(post.validTill, dateFormat));

console.log('Start of next week:', nextWeek);
console.log('Days until:', diff); // 6.xxx (days)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132