How do I format dates from Mongoose in Node.js?

前端 未结 4 1263
借酒劲吻你
借酒劲吻你 2020-12-31 05:10

I\'m trying to change the format of the dates I\'m getting from my Mongo database. Currently they look like this:

Fri Sep 16 2011 19:05:17 GMT+0900 (JST)


        
相关标签:
4条回答
  • 2020-12-31 05:36

    A modern way to do this is to use momentjs, both usable in node and in the browser, super useful and simple to use. For the current problem I solved it like this in node after following all the docs requirements :

    var moment = require('moment');
    var fomatted_date = moment(photo.date_published).format('YYYY-MM-DD');
    

    with photo.date_published directly coming from mongoose.

    0 讨论(0)
  • 2020-12-31 05:36

    what about defining your schema like:

    var someSchema = new Schema({
        title: String,
        created: Date
    });
    

    s.t. the date is stored as a Date object in your mongoDB. As a result, when you read it back you'll have a proper Date object on which you can work with the available methods.

    0 讨论(0)
  • 2020-12-31 05:40

    you have to create a Date object first:

    var date = new Date(dateStr);  // dateStr you get from mongodb
    
    var d = date.getDate();
    var m = date.getMonth()+1;
    // ...
    
    0 讨论(0)
  • 2020-12-31 05:41

    Just Simply Add

    date: { type: String, default: Date }

    Output will be: { "date": "Sat Nov 28 2020 22:57:38 GMT+0530 (India Standard Time)" }

    0 讨论(0)
提交回复
热议问题