문제

I'm somewhat new to JavaScript but I do have some basic understanding. I want to create a countdown timer that will accept a date and a time, but I am unsure how or where to start.

I want the countdown timer to be something like this: http://www.timeanddate.com/clocks/freecountdown.html

So how do I make sure that it works within a specified time zone, with leap years, and DST settings?

도움이 되었습니까?

해결책

Welcome to Stackoverflow!

I'm not going to give everything away, but if you want the time to be unequivocally correct (even if the client's computer is set to the wrong date), you'll have to use something like TimeAPI.

If you want to make sure that it works in a specified timezone, with leap years, etc, the Date object should do the trick:

var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;

To deal with DST, it's more complicated, but the general concensus is just to use the UTC method of the Date object:

 var d=Date.UTC(2012,02,30);

This will make sure you're not crossing any timezone boundaries. There are several questions similar to this one on SO, so feel free to search.

다른 팁

Frankly, you need to study javascript more.

Check out:

Basically, you set the various time parts of a date using functions. Then calculate the difference between the current date and the desired end date (get the milliseconds difference and then calculate a time string to display for remaining time).

Once you have produced some actual code, update your question with it and we might be able to help you more.

This is not really advanced, but it's good start. Example will print, how many days, hours and minutes is left to year 2015.

// NewYearCalculator
// Written by Riku Viitanen
// 2014

today = new Date();

BigDay = new Date("1, 1, 2015");
msPerDay = 24 * 60 * 60 * 1000 ;
timeLeft = (BigDay.getTime() - today.getTime());
e_daysLeft = timeLeft / msPerDay;
daysLeft = Math.floor(e_daysLeft);
e_hrsLeft = (e_daysLeft - daysLeft)*24;
hrsLeft = Math.floor(e_hrsLeft);
minsLeft = Math.floor((e_hrsLeft - hrsLeft)*60);

document.write("Only  " + daysLeft + " days,  " + hrsLeft +" hours and " + minsLeft + " minutes left to year 2015!");

Sorry for my bad English, if it is :3

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top