开发者

Countup Timer with start date as a function variable

I'm new to javascript and was trying to create a countup timer that could take a certain date as an input and count the time that has passed since that date.

I'm currently using a jquery plugin from http://keith-wood.name/countdown.html, but I'm having 2 problems

1) I can't figure out how to add the input date as a function variable. I found another question on this forum that was similar - Jquery Countup Timer, but they were using a fixed date as opposed to a variable input date.

2) How do I ensure that the variable input date conforms to a specific format? Currently I'm trying to read the input date out of a mysql database which timestamps the dates as 2010-06-17 15:12:30, but I don't think that this is the date format that the jquer开发者_JAVA技巧y plugin will read. Is there a way to parse this date so that the formats match up?

Thanks very much to anyone that can help!

Steve


Here is an example.

http://jsfiddle.net/HXf5v/

All you need to do is create a javascript function that takes the Date object as a parameter

something like:

function doDateCountUp(date){
  $('#sinceCountDown').countdown({since: date, compact:true, format: 'YOWDHMS', description: ''});    
}

Alternatively, you could also always create a jquery function.

jQuery.fn.doDateCountUp = function(date){
    $(this).countdown({since: date, compact:true, format: 'YOWDHMS', description: ''});  
}

and then you can invoke the jquery function like so:

$('#mydiv').doDateCountUp(new Date())

As for formatting a new Date() object. you should take a look at:

http://www.w3schools.com/jS/js_obj_date.asp

which states that you can create a date object like this:

new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)


Here is an example taking in the date from a textbox and using it as the startdate:

countup with input exmample

javascript can create a new date by taking in a string in a few different formats. Here's a quick link to those formats: javascript date


To transform the mysql date to a javascript date object:

function mysql2jsdate(mysqlDate){
   var parts = mysqlDate.replace(/:/g, '-').replace(' ', '-').split("-");
   parts = $.map(parts, function(part){ return parseInt(part, 10) });
   return new Date(parts[0], parts[1]-1, parts[2], parts[3], parts[4], parts[5]);
}

Example of usage:

var jsDate = mysql2jsdate('2010-06-17 15:12:30');

Hope this helps to achieve your goal

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜