0

How to check time conditionin Jquery

 var startTime="20:02:55"; // or 12:34
 var endTime ="21:02:55"  // or 1:34 
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();

if(time >startTime || time < endTiime){
 $("#a").html("show Box");
}else{
 $("#a").html("Expire BOx");
}

How to check 12 hour and 24 hour condition also? is it correct? i need am, pm format check please can anyone help me?

Angu
  • 862
  • 2
  • 13
  • 32
  • var hours = date.getHours(); var ampm = hours >= 12 ? 'pm' : 'am'; – Saty Apr 09 '15 at 07:16
  • 3
    You need to also convert `startTime` and `endTime` to Date objects so that they can be easily compared. At the moment you're comparing a Date to a string which is going to give odd results. – Rory McCrossan Apr 09 '15 at 07:18
  • Rory is correct. I'd recommend [momentjs](http://momentjs.com/) for parsing time strings like that. – CodingIntrigue Apr 09 '15 at 07:19
  • @Rory McCrossan please can you answer me the convert starttime and endtime to date? – Angu Apr 09 '15 at 07:22
  • How to check 12 hour and 24 hour also? – Angu Apr 09 '15 at 07:23
  • try this [convert 12-hour hh:mm AM/PM to 24-hour hh:mm](http://stackoverflow.com/questions/15083548/convert-12-hour-hhmm-am-pm-to-24-hour-hhmm) – Smith Foto Apr 09 '15 at 07:47

2 Answers2

2

Here is some code. I am appending to show both behaviour. Here is DEMO

test("20:02:55", "21:02:55");
test("13:02:55", "15:02:55");

function test(start_time, end_time) {
    var dt = new Date();

    //convert both time into timestamp
    var stt = new Date((dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear() + " " + start_time);

    stt = stt.getTime();
    var endt = new Date((dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear() + " " + end_time);
    endt = endt.getTime();

    var time = dt.getTime();

    if (time > stt && time < endt) {
        $("#a").append("<br> show Box ");

    } else {
        $("#a").append("<br> Expire BOx ");

    }
}
rahul maindargi
  • 5,359
  • 2
  • 16
  • 23
1

Try this. I took the logic to print 'Show Box' if the current time is in between the start and end time. else viceversa.

var startTime="20:02:55"; // or 12:34
 var endTime ="21:02:55"  // or 1:34 
var dt = new Date();
var st = new Date('00','00','00',startTime.split(':')[0],startTime.split(':')[1],startTime.split(':')[2]);
var et = new Date('00','00','00',endTime.split(':')[0],endTime.split(':')[1],endTime.split(':')[2]);
if(dt.getTime() >st.getTime() && dt.getTime() < et.getTime()){
alert("show Box");
}else{
alert("Expire BOx");
}