2013-07-26 17 views
10

Quando si utilizzano i bracciali per manubrio Meteor, come si converte l'output di {{ timestamp }} da Thu Jul 25 2013 19:33:19 GMT-0400 (Eastern Daylight Time) a Jul 25?Formato data in Meteor Handlebars bracers {{timestamp}}

provato {{ timestamp.toString('yyyy-MM-dd') }} ma ha dato un errore

+4

Nota: Lo standard [ 'toString()' 'per Date's] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString) ignora qualsiasi argomento passato ad esso e ECMAScript non definisce altri metodi che possono formattare un 'Date' basato su' String' come ''yyyy-MM-dd''. Se non includi già una libreria che modifica 'toString()', dai un'occhiata a http://stackoverflow.com/q/1056728 per i suggerimenti. –

+0

ecco una descrizione migliore di come fare questo -> http://stackoverflow.com/questions/18580495/format-a-date-from-inside-a-handlebars-template-in-meteor –

risposta

37

Utilizzare un aiutante manubrio:

Template.registerHelper("prettifyDate", function(timestamp) { 
    return new Date(timestamp).toString('yyyy-MM-dd') 
}); 

Poi nel tuo html:

{{prettifyDate timestamp}} 

Se si utilizza momento:

Template.registerHelper("prettifyDate", function(timestamp) { 
    return moment(new Date(timestamp)).fromNow(); 
}); 
+6

Come @JonathanLonowski notato sopra, è vale la pena notare che 'timestamp.toString()' ignorerà qualsiasi argomento passato ad esso. Trovo che l'uso di MomentJS rende tutto questo incredibilmente semplice. – Spencer

+3

toDateString() funziona per un formato abbreviato. – user592419

+0

@Akshat, si noti che dopo alcuni flip flopping, la sintassi è ora ['Template.registerHelper'] (http://docs.meteor.com/#/full/template_registerhelper) – KyleMit

1

Questo wor ked for me

+1

Questo non aggiunge nulla alla risposta accettata . –

+0

Non lo so ma, come ricordo, Strings non ha funzionato per me. – user965884

+0

e sopra la risposta è stata aggiornata dopo la mia risposta. – user965884

1

Questo funziona per me.

toString ("aaaa-MM-gg") - non lo converte.

Template.registerHelper("prettifyDate", function(timestamp) { 
    var curr_date = timestamp.getDate(); 
    var curr_month = timestamp.getMonth(); 
    curr_month++; 
    var curr_year = timestamp.getFullYear(); 
    result = curr_date + ". " + curr_month + ". " + curr_year; 
    return result; 
});