Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  13] [ 5]  / answers: 1 / hits: 75574  / 11 Years ago, mon, september 2, 2013, 12:00:00

I got a ISO formatted Date from my Data and what I actually want to do, is to modify my date format directly from my Templates.



like this:



{{format my.context.date myFormat}}


I'm using the moment library, so I could write something like this:



{{formatDate my.context.date DD.MM.YYYY HH:mm}} // 03.09.2013 18:12


It would be nice, because I think it's the place where I should be able to do this. In my template.


More From » datetime

 Answers
35

The solution is quite simple, and maybe someone will find it useful.
In most projects you have a couple of date formats you want to use.
So it's a good approach to define your formats with readable names.


For this example I took just 'short' and 'long', but you will see, it's very easy to extend.


So I created an Object in my Client Script:


var DateFormats = {
short: "DD MMMM - YYYY",
long: "dddd DD.MM.YYYY HH:mm"
};

Also, I created a Handlebars Helper "formatDate".


Edited: Now you should use UI instead of Handlebars


// Deprecated since version 0.8.0 
Handlebars.registerHelper("formatDate", function(datetime, format) {

// Use UI.registerHelper..
UI.registerHelper("formatDate", function(datetime, format) {
if (moment) {
// can use other formats like 'lll' too
format = DateFormats[format] || format;
return moment(datetime).format(format);
}
else {
return datetime;
}
});

As you can see, I use the moment.js lib in my Helper. To install it, just type meteor add momentjs:moment from your command line.


And now, everywhere in my Templates I can use it with the two params, like this:


{{formatDate MyISOString "short"}} // 02 September - 2013
{{formatDate MyISOString "long"}} // Monday 02.09.2013 18:00

If you want to create your own formats, take a look at the momentjs docs http://momentjs.com/docs/


[#75953] Saturday, August 31, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrence

Total Points: 120
Total Questions: 115
Total Answers: 87

Location: England
Member since Fri, May 22, 2020
4 Years ago
terrence questions
Sat, Jun 5, 21, 00:00, 3 Years ago
Wed, Jun 17, 20, 00:00, 4 Years ago
;