ENGR024
ENGR024

Reputation: 317

How to set time to a variable without the date

I am trying to set a specific time to two variables but can't seem to correctly format the syntax. I want to be able to set Shift 1 and Shift 2 off of certain times indicated below.

I want to only be able to use these times in an IF statement so that a radio button can be checked by default. Day Shift button and a Night Shift button. If the current time is in between shift 1, then day shift button is checked.

Date.prototype.currentTime = function(){ 
    return ((this.getHours()>12)?(this.getHours()-12):this.getHours()) +":"+ this.getMinutes()+((this.getHours()>12)?('PM'):'AM'); };

var d1= new Date(); 
var d2 = new Date();
d1.setHours(7);
d1.setMinutes(10);
d2.setHours(19);
d2.setMinutes(10);
alert(d1.currentTime());
alert(d2.currentTime());

Any help is appreciated.

Upvotes: 1

Views: 7323

Answers (3)

kennebec
kennebec

Reputation: 104780

You do not need to compare Date objects for your use, just compare the hours as integers to the integer from now.getHours():

var now= new Date().getHours();
if(now>6 && now<19){
    //check day shift button;
}
// else check niteshift button

Upvotes: 2

Rakesh_Kumar
Rakesh_Kumar

Reputation: 1442

You may try this:

http://jsfiddle.net/apq59j9u/

Date.prototype.currentTime = function(){ 
return ((this.getHours()>12)?(this.getHours()-12):this.getHours()) +":"+ this.getMinutes()+((this.getHours()>12)?('PM'):'AM'); };

var d1= new Date(); 
var d2 = new Date();
d1.setHours(7);
d1.setMinutes(10);
d2.setHours(19);
d2.setMinutes(10);
alert(d1.currentTime());
alert(d2.currentTime());

Upvotes: 1

William Callahan
William Callahan

Reputation: 639

Getting the Data

There are a number of different ways to do this. First here is a way to get the data from the date object:

var d = new Date();
var n = d.toTimeString();

Unfortunately, this will output something like "12:30:30 GMT-0500 (Eastern Standard Time)"

You can also try the getHours() and getMinutes functions to get the hours and minutes in your current timezone.

var d = new Date();
var hours = d.getHours();
var minutes = d.getMinutes();

Setting the Data

This is pretty easy to do, just as getting the data from a date object. Use the following code to set the time to what you would like. Replace the numbers where you see 11 to conform to your needs. NOTE: This time is in military style hours! 1 = 1am, 13 = 1pm, ect.

var d = new Date();
d.setHours(11);
d.setMinutes(11);
d.setSeconds(11);

Result: 11:11:11

Upvotes: 0

Related Questions