1

I am very beginner in JS / JQUERY. I have this code:

var dateFromDB = '2019-12-27 19:12'; // this is data from MySQL

I need compare 2 date/datetime: dateFromDB with actualDataTime - 3 minutes

if (dateFromDB <= (actualDataTime - 3 minutes)]) {
     console.log('user is online');
} else{
console.log('user is offline offline')
}

How can I make it?

2
  • If you have the ability to store your timestamps with a timezone in your database you'll save yourself a lot of headache - especially if you have users that are in different timezones. Commented Dec 28, 2019 at 17:04
  • 1
    Try using momentjs.com, dates are hard in vanilla js. Commented Dec 28, 2019 at 17:22

2 Answers 2

1

You can just substract two Date objects and check the difference in milliseconds:

if (new Date(actualDataTime) - new Date(dateFromDB) <= 3 * 60 * 1000) {
   console.log('user is online');
} else{
   console.log('user is offline offline')
}
Sign up to request clarification or add additional context in comments.

2 Comments

I try yours code: var online = null; var actualDataTime = new Date(); if (new Date(actualDataTime) - new Date(chat[4]) <= 3 * 60 * 1000) { online = 'online'; } else{ online = ''; } but it's not working
@traffka what date format do you use in chat[4] variable? That one you mentioned is working: if (new Date('2019-12-27 19:12') - new Date('2019-12-27 19:05') <= 3 * 60 * 1000) { console.log('user is online'); } else{ console.log('user is offline offline')}
0

You can use momentjs.

After installation:

var dateFromDB = moment('2019-12-27 19:12').format('YYYY-MM-DD hh:mm')
if (dateFromDB >= (moment().subtract(3, 'minutes')).format('YYYY-MM-DD hh:mm')) {
     alert('user is online');
} else{
alert('user is offline')
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.