How to compare time in javascript?

前端 未结 4 1737
忘掉有多难
忘掉有多难 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

    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);

提交回复
热议问题