Home > Software engineering >  If Date is Less Than Current Date by 15mins then do something
If Date is Less Than Current Date by 15mins then do something

Time:12-17

I have been trying to work on something with dates and I was wondering how to check if it is less than 30mins or 15mins difference then should call a function.

let btnCheck = document.querySelector('button');
let result = document.querySeletor('h1');

let current = new Date();
let date = new Date('01/01/2021');

btnCheck.addEventListener('click', () => {
let ms1 = current.getTime();
let ms2 = date.getTime();

result.innerText = ms2 < ms1;
});

So far it results in a true or false but I wanted to add something if the current date is less than the date by 15mis or 30 mins show a button.

Update: Using Moment Library it can be possible through something like this: https://momentjs.com/docs/#/displaying/difference/ But I'm only going to use this for a one-time function.

Thank you in advance! Much appreciated!

CodePudding user response:

You can do something like this -

const btnCheck = document.querySelector('button');
const result = document.querySeletor('h1');

let current = new Date('2011/10/09 12:00');
let date = new Date('2011/10/09 11:30');

btnCheck.addEventListener('click', () => {
    const diff = Math.abs(current - date);
    if (diff === 15 || diff === 30) { // if (diff <= 30) { 
        result.innerText = diff;
        btnCheck.disabled = false;
    }else{
        btnCheck.disabled = true;
    }
});

CodePudding user response:

As Vasyl already said you can use the moment library for this.

If you really want to use pure javascript the documentation of the Date object in JS is pretty good. Take a look here. You have to take into account that the difference is given in milliseconds, thus the calculations. Based on the documentation example i would do it like so (You are free to refactor!):

let btnCheck = document.querySelector('button');
let result = document.querySelector('h1');

let current = new Date();
let date = new Date('01/01/2021');

btnCheck.addEventListener('click', () => {
  let ms1 = current.getTime();
  let ms2 = date.getTime();

  //This checks if the difference is less than 15 minutes
  if((ms1 - ms2) / 1000 / 60 < 15 ){
  };

  //This checks if the difference is less than 30 minutes
  if((ms1 - ms2) / 1000 / 60 < 30 ){
  };
});
  • Related