Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

(Django - Javascript) Timer javascript and datetime python variable in html template

I've found a timer countdown in javascript online and it works fine...

I have to pass python variable to it but, although the result is correct, the countdown doesn't run, it shows the correct remaining time but doesn't continue to decrease (at least I refresh the page)...

These are my piece of codes:

  • views.py
import datetime

auction = Auction.objects.get(id=id)
endDateFormat = auction.endDate.strftime("%Y-%m-%dT%H:%M:%S")
startDateFormat = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
  • template.html

             <script>
                  // Set the date we're counting down to
                  var countDownDate = new Date("{{endDateFormat}}").getTime();
    
                  // Update the count down every 1 second
                  var x = setInterval(function() {
    
                      // Get today's date and time
                      var now = new Date("{{startDateFormat}}").getTime();
    
                      // Find the distance between now and the count down date
                      var distance = countDownDate - now;
    
                      // Time calculations for days, hours, minutes and seconds
                      var days = Math.floor(distance / (1000 * 60 * 60 * 24));
                      var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                      var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
                      // Output the result in an element with id="demo"
                      document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
    
                      // If the count down is over, write some text
                      if (distance < 0) {
                          clearInterval(x);
                          document.getElementById("demo").innerHTML = "EXPIRED";
                      }
                  }, 1000);
              </script>
    

Thanks to everyone!

question from:https://stackoverflow.com/questions/65835487/django-javascript-timer-javascript-and-datetime-python-variable-in-html-temp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...