Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add one second to a time string with javascript/jquery

I am trying to create a timer with Javascript but I don't know how to add one second to a time string.

Time string: 03:31:15

function updateWorked() {
        var time = $("#worked").html();
        ???
        $("#worked").html(wtime);
}

$(document).ready(function() {
    setInterval('updateWorked()', 1000);
});

What should I write in "???" to make this work?

like image 289
Martignoni Avatar asked Sep 22 '26 11:09

Martignoni


2 Answers

Assuming you are using something like PHP to get the time string in the first place, and you can't keep track of the date/time as a number as suggested by Marc B, you can parse the string yourself like this:

var $worked = $("#worked");
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(ss[0]);
dt.setMinutes(ss[1]);
dt.setSeconds(ss[2]);
var dt2 = new Date(dt.valueOf() + 1000);
var ts = dt2.toTimeString().split(" ")[0];
$worked.html(ts);

Edit: Working jsFiddle here of this code.

Here's the code with a timer: jsFiddle

like image 174
Ed Bayiates Avatar answered Sep 24 '26 04:09

Ed Bayiates


Below is an example on how to add a second to a time string. You can use the date object to print out the string in any format that you would like, in this example i'm just using the build in toTimeString method.

var timeString = "10/09/2012 14:41:08";
// start time
var startTime = new Date(timeString);
// prints 14:41:08 GMT-0400 (EDT)
console.log(startTime.toTimeString())
// add a second to the start time
startTime.setSeconds(startTime.getSeconds() + 1);
// prints 14:41:09 GMT-0400 (EDT)
console.log(startTime.toTimeString())
like image 43
Pim Avatar answered Sep 24 '26 02:09

Pim