3

I have a date time in javascript given in format dd.MM.yyyy HH.mm.

What I need to check is whether this date fits in last 24 hours or not.

Example: If date and time now is 06.04.2017 18:26 (dd.MM.yyyy HH.mm) then minimal date allowed to enter is 05.04.2017 18:26. Is it possible to do this check with javascript?

FrenkyB
  • 6,625
  • 14
  • 67
  • 114
  • Possible duplicate of [Javascript code for showing yesterday's date and todays date](http://stackoverflow.com/questions/5495815/javascript-code-for-showing-yesterdays-date-and-todays-date) – Hodrobond Apr 06 '17 at 16:30
  • If you can bring in a library I suggest using MomentJS to do this. https://momentjs.com/docs/#/durations/subtract/ – Stephen Gilboy Apr 06 '17 at 16:32
  • Yes I know for moment.js, but I can't use it right now. – FrenkyB Apr 06 '17 at 16:32

3 Answers3

9

Use the Date object to do what you want - construct a Date object for each date, then compare them using the >, <, <= or >=.

Use of comparison ( ==, !=, ===, and !== ) requires you use date.getTime() as in:

var date1 = new Date();
var date2 = new Date(date1);

var same = date1.getTime() === date2.getTime();
var notSame = date1.getTime() !== date2.getTime();
console.log(same,notSame);

var date1 = new Date('06.04.2017 18:26');
var date2 = new Date('05.04.2017 18:26');

var isGreaterorEq = date1.getTime() >= date2.getTime();
var lessThan = date2.getTime() < date1.getTime();
console.log(isGreaterorEq ,lessThan );

As for the 24 hours thing:

var date1 = new Date('05.06.2017 01:26');
var timeStamp = Math.round(new Date().getTime() / 1000);
var timeStampYesterday = timeStamp - (24 * 3600);
var is24 = date1 >= new Date(timeStampYesterday*1000).getTime();
console.log(is24,timeStamp,date1,timeStampYesterday );
Ben Noland
  • 34,230
  • 18
  • 50
  • 51
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • Beware of UTC if that come into this, I did NOT account for that, lots of answers for that part. – Mark Schultheiss Apr 06 '17 at 17:19
  • Worth noting, I did not test on all browsers but it is my understanding that as of ES5 they should all be consistent i.e. it is likely better to use the ISO 8601 format added in 5.1 standards; Leave that to the OP to investigate as here: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2 – Mark Schultheiss Apr 06 '17 at 17:39
  • date1 should be var date1 = Math.round(new Date('05.06.2017 01:26').getTime()/1000); – Rajilesh Panoli Feb 13 '18 at 19:36
0

First you have convert your date to time stamp. Then you have to do this calculation time stamp(now)-86400 you get the time stamp before 24hrs let us call the variable before_24 Then check your date time stamp if it is > before_24 or no.

Osama
  • 2,912
  • 1
  • 12
  • 15
-4

Yes you can check it with the if condition

if (parseInt(date_variable_data) > parseInt(second_date_variable_data))
{
//do action
}else
{
//do action
}
Rawan-25
  • 1,753
  • 1
  • 17
  • 25