如何比较javascript中的时间? [英] How to compare time in javascript?

查看:179
本文介绍了如何比较javascript中的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两次格式为HH:MM,我想比较他们,我有以下代码以现在的格式获得:

  current_time = new Date(); 
hour = current_time.getHours();
minute = current_time.getMinutes();
if(hour< 10){hour ='0'+ hour} if(minute< 10){minute ='0'+ minute}
my_time = hour +':'+ minute;

此代码是在减去GMT差异后得到时间:

  d = new Date()
var n = d.getTimezoneOffset();
var n1 = Math.abs(n);
var difference =(n1 / 60);
my_time = my_time - (0 +差异);

现在my_time的值应该与match_time的值进行比较:

  match_time = 10:00; //例如
if(my_time> match_time)
{
alert('是');
}
else
{
alert('否');
}

我们如何将这些值作为一个字符串的时间进行比较?

解决方案

使用Date对象。 Date.setHours()允许您指定小时,分钟,秒

  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& amp;& currentD< endHappyHourD){
console.log (是!);
} else {
console.log(no,sorry!between 5.30 pm and 6.30pm);
}


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 = current_time.getHours();
minute = current_time.getMinutes();
if(hour<10){hour='0'+hour} if(minute<10){minute='0'+minute}
my_time = hour+':'+minute;

And this code is to get the time after subtracting the GMT difference :

d = new Date()
var n = d.getTimezoneOffset();
var n1 = Math.abs(n);
var difference = (n1/60); 
my_time = my_time - (0+difference);

Now the value of my_time should be compared with the value of match_time:

match_time = 10:00;//for example
if(my_time > match_time)
{
  alert('yes');
}
else
{
  alert('No');
}

how can I compare those values as time when they are a string ???

解决方案

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

这篇关于如何比较javascript中的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆