Modelesq
Modelesq

Reputation: 5402

Django DateTimeField to a day hour minute second

I'm using http://keith-wood.name/countdown.html. Each 'Event' table in my database has a 'date' column. date = models.DateTimeField() The datetimefield( {{ event.date }}) will return 'Aug. 15, 2012, 12:23 p.m.'. The default plugin format is 'dHMS'.

How do I get my django date to properly display within this jquery plugin? Or better yet. How do I turn my datetimefield into a:

 {{ countdown_day }},
 {{ countdown_hour }},
 {{ countdown_min }},
 {{ countdown_sec }} ?

SCRIPT:

(function(){
     var eventDate = '{{ event.date }}'; 
     $('#defaultCountdown').countdown({until: eventDate});      
     $('#removeCountdown').toggle(function() { 
         $(this).text('Re-attach'); 
         $('#defaultCountdown').countdown('destroy'); 
     }, 
    function() { 
        $(this).text('Remove'); 
        $('#defaultCountdown').countdown({until: eventDate}); 
    });
})();

Upvotes: 2

Views: 3492

Answers (2)

Marco Fedele
Marco Fedele

Reputation: 2148

Actually to obtain a correct date the code is:

new Date({{ countdown|date:"U" }} * 1000);

Because Django return time in seconds, and JS expect time in milliseconds.

Javascript Date object definition

Upvotes: 0

bbrame
bbrame

Reputation: 18554

You can format a Python date into a Django template using the 'date' filter (documentation).

day:     {{ countdown|date:"D" }}
hour:    {{ countdown|date:"g" }}
minute:  {{ countdown|date:"i" }}
second:  {{ countdown|date:"s" }}

To turn the date into a javascript date, I use {{ countdown|date:"U" }} to get the unix timestamp. You can create a javascript date object from this as follows:

 new Date({{ countdown|date:"U" }} / 1000);

Upvotes: 4

Related Questions