raeq
raeq

Reputation: 971

Is there a way to increment time using javascript?

So I am storing times as '01:30:00'. I have a start time and a date time dropdown. I want the dropdown to be set to the start time + 1hr. Is there a way to add the time via javascript or jquery?

Here's my current code:

$(".start_time").change(function(){
        $(".end_time").val($(this).val());
});

Upvotes: 2

Views: 5452

Answers (4)

p.campbell
p.campbell

Reputation: 100577

Try this:

  • find the selected index of the start time
  • bump it up by 2 to find your end time index (given that you've got half hour increments)
  • use the mod operator % to wrap back to index 0 or 1 (for 00:00 and 00:30 respectively)
$(".start_time").change(function(){
        var sel =$(this).attr('selectedIndex');
        var endIdx = (sel + 2) % 48; // 47 is 23:30, so 48 should go back to index 0
        $(".end_time").attr('selectedIndex', endIdx);        
});

Try it out on JSBin.

Upvotes: 3

Domenic
Domenic

Reputation: 112827

There are two separate problems here: the first is parsing out the time from your .start_time input, and the second is incrementing it to be an hour later.

The first is really a string-manipulation exercise. Once you have parsed out the pieces of the string, e.g. via a regex, you could either turn them into a Date instance and use setHours, or you could just manipulate the components as numbers and them reassemble them into a string in the format you desire.

An example of this might be as follows:

var TIME_PARSING_REGEX = /([0-9]{2}):([0-9]{2}):([0-9]{2})/;

function padToTwoDigits(number) {
    return (number < 10 ? "0" : "") + number;
}

$(".start_time").change(function () {
    var stringTime = $(this).val();
    var regexResults = TIME_PARSING_REGEX.exec(stringTime);

    var hours = parseInt(regexResults[1], 10);
    var newHours = (hours + 1) % 24;

    var newHoursString = padToTwoDigits(newHours);
    var minutesString = regexResults[2];
    var secondsString = regexResults[3];

    var newTimeString = newHoursString + ":" + minutesString + ":" + secondsString;
    $(".end_time").val(newTimeString);
});

Upvotes: 1

emyller
emyller

Reputation: 2746

After you parse you date/time string, you can use methods such as .setHours in your date object (more info at Mozilla Developer Center).

I highly recommend the DateJS library for working with date and time. I'm sure it'll be very handy for you.

protip: try to avoid replacing JavaScript with "jQuery markup"; it's all JS, after all. :)

Upvotes: 0

wdm
wdm

Reputation: 7189

Basic example...

var date = new Date();
var h = date.getHours() + 1;
var m = date.getMinutes();
var s = date.getSeconds();
alert('One hour from now: ' + h + ':' + m + ':' + s);

Demo: http://jsfiddle.net/fBaDM/2/

Upvotes: 0

Related Questions