Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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())

If you're trying to keep a counter in real time, you should use new Date() to get the time, and then format it:

function updateWorked() {
    var time = new Date(),
        wtime = formatDate(time);
    $("#worked").html(wtime);
}

However, if you're trying to keep a specific time, then you should up-scope a Date object and use that:

var time = new Date(/* your starting time */);
function updateWorked() {
    time.setTime(time.getTime()+1000);
    var wtime = formatDate(time);
    $("#worked").html(wtime);
}

Also, you'd want to add a formatDate function:

function formatDate(date) {
  var hours = date.getHours().toString();
  if (hours.length < 2) hours = '0'+hours;
  var minutes = date.getMinutes().toString();
  if (minutes.length < 2) minutes = '0'+minutes;
  var seconds = date.getSeconds().toString();
  if (seconds.length < 2) seconds = '0'+seconds;
  return hours+':'+minutes+':'+seconds;
}

Using mixture of jquery and javascript you can achieve this example.

I tired to achive what you looking for, first created a date object and get all the values of time, minute and second and then replaced the value. Please have a look at jsfiddle

DEMO

http://jsfiddle.net/saorabhkr/xtrpK/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top