1 Replies - 1272 Views - Last Post: 04 October 2012 - 04:31 PM

Timetables in Javascript

Posted 04 October 2012 - 03:51 PM

Ok so I can do a timetable no bother in HTML and CSS but Javascript is proving to be more tricky.
The table is OK the difficulty I'm having is I'm supposed to show how many days left are to my exam.
I already have the date today but how would you solve it for days ago or even hours ago?

Replies To: Timetables in Javascript

Re: Timetables in Javascript

Posted 04 October 2012 - 04:31 PM

You can use the Date.now() and Date.parse() functions to get timestamps. Those are usually easier to work with when you need to do things like find time spans. For instance, to print the date two days ago you can do:

// Get the Unix timestamp representing the current time.
var current_timestamp = Date.now();
// Calculate how many milliseconds there are in two days.
var two_days = (1000 * 60 * 60 * 24 * 2);
// Calculate the timestamp two days ago.
var two_days_ago = current_timestamp - two_days;
// Show the formatted date in some element.
target.innerHTML = new Date(two_days_ago);

Using those two functions, you can get the timestamp for your end date, and the current timestamp, and using those calculate how many milliseconds there are between them. Then it's just a matter of calculating the days, hours, minutes and seconds (or whichever measurements you're interested in) that number of milliseconds represents.