How do I display todays date in Node.js Jade?

前端 未结 7 1356
囚心锁ツ
囚心锁ツ 2021-01-31 15:04

I am new to Node.js and Jade and I have tried to use #{Date.now()} and it\'s giving me numbers. How do I display the date in mm/dd/yy format?

7条回答
  •  生来不讨喜
    2021-01-31 15:46

    You will need to use the methods on the Date object to achieve what you're after. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date

    For example, the code below should do what you need:

    var dateNow = new Date();
    var dd = dateNow.getDate();
    var monthSingleDigit = dateNow.getMonth() + 1,
        mm = monthSingleDigit < 10 ? '0' + monthSingleDigit : monthSingleDigit;
    var yy = dateNow.getFullYear().toString().substr(2);
    
    var formattedDate = mm + '/' + dd + '/' + yy;
    

    So if you were using say jade with express and node you could do something like:

    res.render('jadeTemplateName', { 
        dateNow: function() {
            var dateNow = new Date();
            var dd = dateNow.getDate();
            var monthSingleDigit = dateNow.getMonth() + 1,
                mm = monthSingleDigit < 10 ? '0' + monthSingleDigit : monthSingleDigit;
            var yy = dateNow.getFullYear().toString().substr(2);
    
            return (mm + '/' + dd + '/' + yy);
        } 
    })
    

    and in your jade template say if you wanted to add the date to a span:

    span Today's date is #{dateNow()}
    

提交回复
热议问题