1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
| <style>
html,
body {
margin: 0;
padding: 0;
}
#header {
text-align: center;
font-size: 20px;
width: 100%;
height: 50px;
line-height: 50px;
background: white;
border-bottom: 1px solid black;
}
#content {
text-align: center;
top: 25px;
position: absolute;
overflow: auto;
line-height: 25px;
}
</style>
<div id="header">
<span id="counter1"><strong>16</strong> дней </span>
</div>
<div id="content"></div>
<script>
function Counter(initDate, id){
this.counterDate = 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();
}
Counter.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));
}
Counter.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);
}
Counter.prototype.calculate=function(){
var futureDate = this.counterDate > new Date()? this.counterDate : new Date();
var pastDate = this.counterDate == futureDate? new Date() : this.counterDate;
this.seconds = this.datePartDiff(pastDate.getSeconds(), futureDate.getSeconds(), 60);
this.minutes = this.datePartDiff(pastDate.getMinutes(), futureDate.getMinutes(), 60);
this.hours = this.datePartDiff(pastDate.getHours(), futureDate.getHours(), 24);
this.days = this.datePartDiff(pastDate.getDate(), futureDate.getDate(), this.numOfDays[futureDate.getMonth()]);
this.months = this.datePartDiff(pastDate.getMonth(), futureDate.getMonth(), 12);
this.years = this.datePartDiff(pastDate.getFullYear(), futureDate.getFullYear(), 0);
}
Counter.prototype.addLeadingZero=function(value){
return value < 10 ? ("0" + value) : value;
}
Counter.prototype.formatTime=function(){
this.seconds = this.addLeadingZero(this.seconds);
this.minutes = this.addLeadingZero(this.minutes);
this.hours = this.addLeadingZero(this.hours);
}
Counter.prototype.updateCounter=function(){
this.calculate();
this.formatTime();
this.countainer.innerHTML = "Прошел" + " <strong>" + this.days + "</strong> " + (this.days == 1? "день" : "дня");
var self = this;
setTimeout(function(){self.updateCounter();}, 1000);
}
</script>
<script type="text/javascript">
new Counter('September 25, 2018 00:00:00', 'counter1');
new Counter(((new Date()).getTime()+10000), 'counter2');
</script> |