Reputation:
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.
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
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')
});
Upvotes: 1
Reputation: 5685
How about this little formula:
date.getHours() * 100 + date.getMinutes()
Upvotes: 4