How to compare time in javascript?

前端 未结 4 1736
忘掉有多难
忘掉有多难 2020-12-31 04:14

I have two time in the format \"HH:MM\" i want to compare them i have the following code to get the time of now in my format:

current_time = new Date();
hour         


        
相关标签:
4条回答
  • 2020-12-31 04:39

    use Date objects. Date.setHours() allows you to specify hour, minutes, seconds

    var currentD = new Date();
    var startHappyHourD = new Date();
    startHappyHourD.setHours(17,30,0); // 5.30 pm
    var endHappyHourD = new Date();
    endHappyHourD.setHours(18,30,0); // 6.30 pm
    
    console.log("happy hour?")
    if(currentD >= startHappyHourD && currentD < endHappyHourD ){
        console.log("yes!");
    }else{
        console.log("no, sorry! between 5.30pm and 6.30pm");
    }
    
    0 讨论(0)
  • 2020-12-31 04:39

    Similar to @Arjun Sol, instead of using Date.parse, you could just grab the times from the string itself, create a new Date object and do the comparison.

    const time1 = '12:42';
    const time2 = '18:30';
    
    const getTime = time => new Date(2019, 9, 2, time.substring(0, 2), time.substring(3, 5), 0, 0);
    
    const result = getTime(time1) < getTime(time2);
    console.log('This should be true:', result);
    0 讨论(0)
  • 2020-12-31 04:44
    Date.parse('25/09/2013 13:31') > Date.parse('25/09/2013 9:15')
    

    EDIT:

    Note that you are parsing an arbitrary date that you're not interested in, it just needs to be the same on both sides.

    0 讨论(0)
  • 2020-12-31 04:57
     if(Date.parse('01/01/2011 10:20:45') == Date.parse('01/01/2011 5:10:10')) {
      alert('same');
      }else{
    
      alert('different');
    
      }
    
    The 1st January is an arbitrary date, doesn't mean anything.
    
    0 讨论(0)
提交回复
热议问题