Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Web программирование > JavaScript, Ajax
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 05.11.2014, 20:10   #1
romantik1993
Пользователь
 
Регистрация: 12.03.2012
Сообщений: 99
Восклицание Исправить таймер

У меня есть код таймера отсчета от определенной даты...исправьте его пожалуйста или предложите свой....таймер функционирует, но есть одно но ....если там к примеру 1 год то он выводит один год, а все остальные значения он выводит как "лет" (2 лет, 4 лет, 10 лет и т.д.)....исправьте пожалуйста .......тоесть мне нужно чтобы если число оканчивается на 1 то выводится год, месяц, неделя, день, час, секунда, а если оканчивается на 2,3,4 то пишет года, месяца, недели, дня, часа, секунды, а если оканчивается число на 0,5,6,7,8,9 то пишет лет, месяцев, недель, дней,часов, секунд. скриншот получаемого мной таймера приведу ниже.

Вот скрипт который нужно исправить
Код HTML:
<script type="text/javascript">
 
function CountUp(initDate, id){
 this.beginDate = new Date(initDate);
 this.countainer = document.getElementById(id);
 this.numOfDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
 this.borrowed = 0, this.years = 0, this.months = 0, this.days = 0;
 this.hours = 0, this.minutes = 0, this.seconds = 0;
 this.updateNumOfDays();
 this.updateCounter();
}
 
CountUp.prototype.updateNumOfDays=function(){
 var dateNow = new Date();
 var currYear = dateNow.getFullYear();
 if ( (currYear % 4 == 0 && currYear % 100 != 0 ) || currYear % 400 == 0 ) {
 this.numOfDays[1] = 29;
 }
 var self = this;
 setTimeout(function(){self.updateNumOfDays();}, (new Date((currYear+1), 1, 2) - dateNow));
}
 
CountUp.prototype.datePartDiff=function(then, now, MAX){
 var diff = now - then - this.borrowed;
 this.borrowed = 0;
 if ( diff > -1 ) return diff;
 this.borrowed = 1;
 return (MAX + diff);
}
 
CountUp.prototype.calculate=function(){
 var currDate = new Date();
 var prevDate = this.beginDate;
 this.seconds = this.datePartDiff(prevDate.getSeconds(), currDate.getSeconds(), 60);
 this.minutes = this.datePartDiff(prevDate.getMinutes(), currDate.getMinutes(), 60);
 this.hours = this.datePartDiff(prevDate.getHours(), currDate.getHours(), 24);
 this.days = this.datePartDiff(prevDate.getDate(), currDate.getDate(), this.numOfDays[currDate.getMonth()]);
 this.months = this.datePartDiff(prevDate.getMonth(), currDate.getMonth(), 12);
 this.years = this.datePartDiff(prevDate.getFullYear(), currDate.getFullYear(),0);
}
 
CountUp.prototype.addLeadingZero=function(value){
 return value < 10 ? ("0" + value) : value;
}
 
CountUp.prototype.formatTime=function(){
 this.seconds = this.addLeadingZero(this.seconds);
 this.minutes = this.addLeadingZero(this.minutes);
 this.hours = this.addLeadingZero(this.hours);
}
 
CountUp.prototype.updateCounter=function(){
 this.calculate();
 this.formatTime();
 this.countainer.innerHTML ="<strong>" + this.years + "</strong> <small>" + (this.years == 1? "год" : "года") + "</small>" +
 " <strong>" + this.months + "</strong> <small>" + (this.months == 1? "месяц" : "месяца") + "</small>" +
 " <strong>" + this.days + "</strong> <small>" + (this.days == 1? "день" : "дней") + "</small>" +
 " <strong>" + this.hours + "</strong> <small>" + (this.hours == 1? "час" : "часов") + "</small>" +
 " <strong>" + this.minutes + "</strong> <small>" + (this.minutes == 1? "минута" : "минут") + "</small>" +
 " <strong>" + this.seconds + "</strong> <small>" + (this.seconds == 1? "секунда" : "секунд") + "</small>";
 var self = this;
 setTimeout(function(){self.updateCounter();}, 1000);
}
 
window.onload=function(){ new CountUp('Jul 01, 2010 00:00:00', 'counter'); }
 
</script>
<div id="counter"><span style="font-size:20px;">Загрузка таймера</span></div>
romantik1993 вне форума Ответить с цитированием
Старый 05.11.2014, 20:10   #2
romantik1993
Пользователь
 
Регистрация: 12.03.2012
Сообщений: 99
По умолчанию

А вот пример таймера который должен быть , только это таймер обратного отсчета, а мне нужен прямого

Код HTML:
<script>
onload = function ()
{
setInterval (function ()
{
var fY = 2015, fM = 10, fD = 1, fH = fm = fS = 0;                       // 1 ноября 2015 года, полночь
 
var nT = new Date ().getTime ();
 
var Y = 0; while (new Date (fY - Y, fM    , fD    , fH    , fm    , fS    ).getTime () > nT) Y++; Y--;
var M = 0; while (new Date (fY - Y, fM - M, fD    , fH    , fm    , fS    ).getTime () > nT) M++; M--;
var D = 0; while (new Date (fY - Y, fM - M, fD - D, fH    , fm    , fS    ).getTime () > nT) D++; D--;
var H = 0; while (new Date (fY - Y, fM - M, fD - D, fH - H, fm    , fS    ).getTime () > nT) H++; H--;
var m = 0; while (new Date (fY - Y, fM - M, fD - D, fH - H, fm - m, fS    ).getTime () > nT) m++; m--;
var S = 0; while (new Date (fY - Y, fM - M, fD - D, fH - H, fm - m, fS - S).getTime () > nT) S++; S--;
 
function addText (n, w)
{
var j, e = n.toString ().slice (-1);
     if (!n) return ' ';
     if (n > 10 && n < 20) j = 2;
else if (e == 0)           j = 2;
else if (e == 1)           j = 0;
else if (e < 5 )           j = 1;
else                       j = 2;                            
return n + ' ' + w [j];
}
 
Y = addText (Y, ['год'    , 'года'   , 'лет'    ]),
M = addText (M, ['месяц'  , 'месяца' , 'месяцев']),
D = addText (D, ['день'   , 'дня'    , 'дней'   ]),
H = addText (H, ['час'    , 'часа'   , 'часов'  ]),
m = addText (m, ['минута' , 'минуты' , 'минут'  ]),
S = addText (S, ['секунда', 'секунды', 'секунд' ]);
 
document.getElementById ('digital_watch').innerHTML = ([Y, M, D, H, m, S].join (' '));
}, 1000);
}
</script>
 
<p id="digital_watch"></p>
romantik1993 вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Таймер kort95 Общие вопросы Delphi 12 12.12.2013 22:13
Таймер ЕгорКр Общие вопросы Delphi 6 05.06.2013 22:33
Таймер SashaKrugliak Помощь студентам 3 24.10.2011 08:13
Таймер Shift_sk Паскаль, Turbo Pascal, PascalABC.NET 9 10.01.2011 15:02
Таймер Ins1De Общие вопросы C/C++ 2 26.05.2010 22:29