user1752532
user1752532

Reputation:

If else statement based on Date()

I have a script that writes an if else statement based on the time of day. I was having trouble creating a timestamp from the Date() function in javascript and had to write what i think is really verbose code. I first have to create a proper string ( in that i need the "0" to appear before numbers < 10 so that i can get a round time number i.e 1204 for 12:04 and then base the if else statement on that concat which is odd because i first have to parse it has a string and then parse it back as int.

jsfiddlething

 var minExtra = min < 10 ? '0' + min : min;
 var intConcat = (hour).toString() + minExtra;
 var now = parseInt(intConcat);

I tried searching for solutions, but i dont think i am searching for the correct terms

My question is basically, can this if else statement be written without, what seems to be verbose code, and base the if else statement on an actual time and not a number representation of the time?

Upvotes: 0

Views: 548

Answers (2)

KooiInc
KooiInc

Reputation: 122898

To reduce most of the verbosity, you could rewrite your method to:

$('button').click(function () {
     var now = (function(){return this.getHours()*100 + this.getMinutes();})
                .call(new Date);
     alert( now < 1200 && '1' || now < 1300 && '2' || now < 1400 && '3')
});

JsFiddle

Upvotes: 1

Matthew Mcveigh
Matthew Mcveigh

Reputation: 5685

How about this little formula:

date.getHours() * 100 + date.getMinutes()

Upvotes: 4

Related Questions