Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trying to format a date on jade template

Tags:

node.js

pug

I have an index.js:

exports.index = function(req, res){
  db.courses.find(function(err, currentCourses) {
    res.render('index', {
      currentCourses: currentCourses
    });
  });
};

And on my jade template:

tr
    td #{currentCourses[0].start}

Which is a date, formatted as "Sun Sep 29 2013 00:00:00 GMT+0100 (BST)".

How can I format it to "29 Sep 2013"?

Edit (after Ed Hinchliffe's comments):

-function prettyDate(dateString){
    -var d = date.getDate(dateString);
    -var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
    -var m = monthNames[date.getMonth()];
    -var y = date.getFullYear();
    -return d+' '+m+' '+y;
-} 
for course in currentCourses
    tr
        td #{prettyDate(course.start)}
like image 896
babbaggeii Avatar asked Jun 04 '13 16:06

babbaggeii


2 Answers

My solution is:

Add momentjs to your express application locals like this:
app.locals.moment = require('moment');

Then you can use moment in any jade files:
span='(Created at: ' + moment(obj.createTime).format("YYYY/MM/DD") + ')'

Reference:
Making use of utility libraries in server-side Jade templates

like image 55
Zhifeng Hu Avatar answered Oct 06 '22 00:10

Zhifeng Hu


Not particularly easy unfortunately. You'll need a function to format a string either inside your template, or outside (and pass the pretty string).

Something like this (JADE)

-function prettyDate(dateString){
    //if it's already a date object and not a string you don't need this line:
    -var date = new Date(dateString);
    -var d = date.getDate();
    -var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
    -var m = monthNames[date.getMonth()];
    -var y = date.getFullYear();
    -return d+' '+m+' '+y;
-}


tr
   td #{prettyDate(currentCourses[0].start)}
like image 22
Ed_ Avatar answered Oct 05 '22 23:10

Ed_