125

Is there a way to check if a date is less than 1 hour ago like this?

// old date
var olddate = new Date("February 9, 2012, 12:15");

// current date
var currentdate = new Date();

if (olddate >= currentdate - 1 hour) {
    alert("newer than 1 hour");
else {
    alert("older than 1 hour");
}

Also, different question - is there a way to add hours to a date like this?

var olddate = new Date("February 9, 2012, 12:15") + 15 HOURS; // output: February 10, 2012, 3:15
KyleMit
  • 30,350
  • 66
  • 462
  • 664
supercoolville
  • 8,636
  • 20
  • 52
  • 69
  • your second question is a possible duplicate of http://stackoverflow.com/questions/1050720/adding-hours-to-javascript-date-object – Pbirkoff Feb 10 '12 at 08:26

8 Answers8

214

Define

var ONE_HOUR = 60 * 60 * 1000; /* ms */

then you can do

((new Date) - myDate) < ONE_HOUR

To get one hour from a date, try

new Date(myDate.getTime() + ONE_HOUR)                       
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
76

Using some ES6 syntax:

const lessThanOneHourAgo = (date) => {
    const HOUR = 1000 * 60 * 60;
    const anHourAgo = Date.now() - HOUR;

    return date > anHourAgo;
}

Using the Moment library:

const lessThanOneHourAgo = (date) => {
    return moment(date).isAfter(moment().subtract(1, 'hours'));
}

Shorthand syntax with Moment:

const lessThanOneHourAgo = (date) => moment(date).isAfter(moment().subtract(1, 'hours'));
jklp
  • 2,091
  • 2
  • 23
  • 37
Gorka Hernandez
  • 3,890
  • 23
  • 29
  • 2
    This also works with [dayjs](https://github.com/iamkun/dayjs). `const lessThanOneHourAgo = (date) => { return dayjs(date).isAfter(dayjs().subtract(1, 'hours')); };` – turrican_34 Nov 26 '19 at 15:54
  • This was pretty close to what I needed. which was moreThanXHours ago, so I just added isBefore instead of isAfter! – Urasquirrel Mar 23 '20 at 17:18
10

the moment library can really help express this. The trick is to take the date, add time, and see if it's before or after now:

  lastSeenAgoLabel: function() {
    var d = this.lastLogin();
    if (! moment(d).isValid()) return 'danger';  // danger if not a date.
    if (moment(d).add(10, 'minutes').isBefore(/*now*/)) return 'danger'; // danger if older than 10 mins
    if (moment(d).add(5,  'minutes').isBefore(/*now*/)) return 'warning'; // warning if older than 5mins
    return 'success';  // Looks good!
  },
Michael Cole
  • 15,473
  • 7
  • 79
  • 96
3

Using moment will be much easier in this case, You could try this:

    let hours = moment().diff(moment(yourDateString), 'hours');

It will give you integer value like 1,2,5,0etc so you can easily use condition check like:

if(hours < 1) {

Also, one more thing is you can get more accurate result of the time difference (in decimals like 1.2,1.5,0.7etc) to get this kind of result use this syntax:

let hours = moment().diff(moment(yourDateString), 'hours', true);

Let me know if you have any further query

Umang Loriya
  • 840
  • 8
  • 15
1

You can do it as follows:

  1. First find difference of two dates i-e in milliseconds
  2. Convert milliseconds into minutes
  3. If minutes are less than 60, then it means date is within hour else not within hour.
var date = new Date("2020-07-12 11:30:10");
var now = new Date();
var diffInMS = now - date;
var msInHour = Math.floor(diffInMS/1000/60);
if (msInHour < 60) {
    console.log('Within hour');
} else {
    console.log('Not within the hour');
}
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Tanzeem Bhatti
  • 219
  • 2
  • 3
1
//for adding hours to a date
Date.prototype.addHours= function(hrs){
    this.setHours(this.getHours()+hrs);
    return this;
}

Call function like this:

//test alert(new Date().addHours(4));
animuson
  • 53,861
  • 28
  • 137
  • 147
Krishna N
  • 216
  • 1
  • 2
  • 7
0

Plain JavaScript solution with in 12 days and 12 days ago option

const timeAgo = ( inputDate ) => {

  const date = ( inputDate instanceof Date) ? inputDate : new Date(inputDate);

  const FORMATTER = new Intl.RelativeTimeFormat('en');
  const RANGES = {
    years   : 3600 * 24 * 365,
    months  : 3600 * 24 * 30,
    weeks   : 3600 * 24 * 7,
    days    : 3600 * 24,
    hours   : 3600,
    minutes : 60,
    seconds : 1
  };
  
  const secondsElapsed = (date.getTime() - Date.now()) / 1000;
  
  for (let key in RANGES) {
    if ( RANGES[key] < Math.abs(secondsElapsed) ) {
      const delta = secondsElapsed / RANGES[key];
      return FORMATTER.format(Math.round(delta), key);
    }
  }
  
}




// OUTPUTS
console.log( timeAgo('2040-12-24') )
console.log( timeAgo('6 Sept, 2012') );
console.log( timeAgo('2022-05-27T17:45:01+0000') );

let d = new Date() 
console.log( "Date will change: ", timeAgo( d.setHours(24,0,0,0) ) );
    // d.setDate( d.getDate() - 0 );
    d.setHours(-24,0,0,0); // (H,M,S,MS) | 24 hours format 
console.log("Day started: " , timeAgo( d ) );
GMKHussain
  • 3,342
  • 1
  • 21
  • 19
-3

//try this: // to compare two date's:

<Script Language=Javascript>
function CompareDates() 
{ 
    var str1 = document.getElementById("Fromdate").value;
    var str2 = document.getElementById("Todate").value;
    var dt1  = parseInt(str1.substring(0,2),10); 
    var mon1 = parseInt(str1.substring(3,5),10);
    var yr1  = parseInt(str1.substring(6,10),10); 
    var dt2  = parseInt(str2.substring(0,2),10); 
    var mon2 = parseInt(str2.substring(3,5),10); 
    var yr2  = parseInt(str2.substring(6,10),10); 
    var date1 = new Date(yr1, mon1, dt1); 
    var date2 = new Date(yr2, mon2, dt2); 

    if(date2 < date1)
    {
        alert("To date cannot be greater than from date");
        return false; 
    } 
    else 
    { 
        alert("Submitting ...");
    } 
} 

</Script>

Hope it will work 4 u...

Krishna N
  • 216
  • 1
  • 2
  • 7