0


I am newbie and need ur help. I have a problem on finding out days, hours, minutes and seconds. I dont know what to update minutes after seconds will reach 60 and same with hours and days.
I am trying to countdown to a given date in a format of Days/Hours/Minutes/Seconds.
Here is the link of what I've done so far.
Thnx in advance! :)

FoxKllD
  • 971
  • 3
  • 13
  • 22

3 Answers3

3
var seconds = 1355998990 - new Date().getTime(), // whatever
minutes = Math.floor(seconds/60),
hours = Math.floor(minutes/60),
days = Math.floor(hours/24);

seconds %= 60;
minutes %= 60;
hours %= 24;

console.log("d: " + days + " h: " + hours + " m: " + minutes + " s: " + seconds);

Will this do?

Also make sure to check out this; maybe you can get some inspiration there.

Harti
  • 1,480
  • 12
  • 16
2

why don't you use one of the many plugins available to do the trick, consider the following links:

http://keith-wood.name/countdown.html

this one is listing many plugins for the same purpose, use any of them and smile :) http://www.tripwiremagazine.com/2012/01/jquery-countdown-scripts.html

Mohammed Swillam
  • 9,119
  • 4
  • 36
  • 47
1

I've modified your count_execution function and added some comments. It should do what you ask.

function count_execution() {
  // target date of event
  var eventDate   = new Date(settings.date);
  // now
  var currentDate = new Date();
  // get date diff *in milliseconds*
  var diff   = Math.abs(currentDate - eventDate);

  // compute days left
  // 24h * 60m * 60s * 1000 = 86400000
  var days = Math.floor(diff / 86400000);
  diff = diff % 86400000;

  // compute hours left
  // 60m * 60s * 1000 = 3600000
  var hours = Math.floor(diff / 3600000);
  diff = diff % 3600000;

  // the same for minutes
  var minutes = Math.floor(diff / 60000);
  diff = diff % 60000;

 // finally, seconds
 var seconds = Math.floor(diff / 1000);

 $this.find('#days').text(days);
 $this.find('#hours').text(hours);
 $this.find('#mins').text(minutes);
 $this.find('#secs').text(seconds);
}

Hope it helps.

  • Ye, I got what I wanted, but is there an easier way of getting hours, minutes and seconds using jQuery? – FoxKllD Mar 08 '12 at 23:18
  • I think that probably your best bet would be using a jQuery plugin like @Mohammed suggested. Strictly speaking about date manipulation and formatting I recently discovered [Moment.js](http://momentjs.com) and it's been very useful to me. – Estanislau Trepat Mar 09 '12 at 09:44