Reputation: 12512
OK, I've resisted to post this question but I can't explain the results I'm getting, so here it is:
I have get a time value in a military format, like 16:00. From this I need to get 3 different hours:
So expected result will be:
`
var timeRes = $(this).data('time'),
timeGet = timeRes.split(':'),
hourGet = timeGet[0],
minsGet = timeGet[1],
hourBfo = (hourGet-1),
hourNxt = (hourGet++);`
Seems pretty basic, however, when I test and out put the following:
console.log(timeRes+' -- Get: '+timeGet + ' -- Bfo: '+hourBfo+' -- Now: '+hourGet+' -- Nxt: '+hourNxt+' -- Mins: '+minsGet);
I get this:
16:00 -- Get: 16,00 -- Bfo: 15 -- Now: 17 -- Nxt: 16 -- Mins: 00
Notice, Now and Nxt are flipped. What am I missing?...
Upvotes: 0
Views: 813
Reputation: 635
I would do something like:
var time = '16:00';
var hour = time.split(':')[0];
var previousHour = hour - 1;
var nextHour = hour + 1;
The difference being if you use a ++ operator, you should learn how it works. It basically applies the increment after the command is done. So, the code:
var i=7;
console.log(i++);
console.log(i);
Will output: 7 8
I hope this helps.
Mario
Upvotes: 0
Reputation: 1395
hourNxt = (hourGet++);
basically means "set hourNxt
to what hourGet
currently is, and then increase the value of hourGet
by one."
What you want is hourNxt = hourGet + 1
.
Upvotes: 1
Reputation: 7482
You have 2 errors here. First, you should convert your splitted strings to integer, so there'd no strange effects while doing math operations with them:
hourGet = parseInt(timeGet[0]), minsGet = parseInt(timeGet[1])
Secondly, hourNxt = (hourGet++)
works this way:
hourGet
to hourNxt
.hourGet
value by 1.That's why you're getting these results. You don't need ++
operator here (you don't want to change hourGet
, do you?), just use plain old:
hourNxt = hourGet + 1
Upvotes: 4