MomentJS comparing Unix time with minutes and get difference

Viewed 475

I need to find if currentDate time (unix) and lastFetchedTime(unix) is greater than 30 minutes in moment.js.

How can compare the subtracted value from 30 minutes in moment?

lastFetchedTime(unix) is equivalent to the previous Date.now()..

const now = moment(Date.now());

const lastFetched = 1598578706;
const checkTime = now.diff(lastFetched, 'minutes') > 30 ;

1 Answers

You can use momentJS duration function to get the difference between two times which are in unix format.

Firstly, you need to convert the unix format to human readable time and then get the difference of current time and lastFetched time using asMinutes function of duration

If the difference is greater then 30 then do something else or do something else.

Live Demo:

const now = moment().unix()
const lastFetched = 1598597404; 
const duration = moment.duration(moment.unix(now).diff(moment.unix(lastFetched)));
const getMinutes = duration.asMinutes();

if (getMinutes > 30) {
  console.log('Minutes are GREATER then 30 minutes - from now')
} else {
  console.log('Minutes are LESS then 30 minutes - from now')
}
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.js"></script>

Related