Try this! Given a view
:
def timer_page_view(request):
auction = Auction.objects.last()
context = {
'start_date': auction.start_date.strftime("%Y-%m-%dT%H:%M:%S"),
'end_date': auction.end_date.strftime("%Y-%m-%dT%H:%M:%S"),
}
return render(request, 'timer_page.html', context=context)
Your timer_page.html
template could look like this:
<body>
<p>start date is {{ start_date }}</p>
<p>start date is {{ end_date }}</p>
<div id='demo'>time difference</div>
</body>
<script>
// Set the date we are counting to
var countDownDate = new Date('{{ end_date }}');
// Set the date we are counting from
var countFromDate = new Date("{{ start_date }}");
// Set inital distance in seconds
var distance = (countDownDate.getTime() - countFromDate.getTime()) / 1000;
// Set initial time difference in the DOM
var days = Math.floor((distance / (60 * 60 * 24)));
var hours = Math.floor((distance - (days * (60 * 60 * 24))) / (60 * 60));
var minutes = Math.floor((distance - ((days * (60 * 60 * 24)) + (hours * (60 * 60)))) / 60);
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("demo").innerHTML = days + ' ' + hours + ' ' + minutes + ' ' + seconds;
// Timer
let active = true;
startTimer = () => {
if (active) {
var timer = document.getElementById("demo").innerHTML;
let nums = timer.split(" ").map(num => parseInt(num))
let day = nums[0];
let hour = nums[1];
let min = nums[2];
let sec = nums[3];
if (sec == 0) {
if (min == 0) {
hour--;
min = 59;
if (hour == 0){
day--;
hour = 23;
}
if (hour < 10) hour = "0" + hour;
} else {
min--;
}
if (min < 10) min = "0" + min;
sec = 59;
} else {
sec--;
console.log(sec)
if (sec < 10) sec = "0" + sec;
}
document.getElementById("demo").innerHTML = day + ' ' + hour + ' ' + min + ' ' + sec;
setTimeout(startTimer, 1000);
}
}
startTimer();
</script>
The timer would start immediately here, but you can play around with that to your liking.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…