Munsterberg
Munsterberg

Reputation: 828

Format date before submitting to mongoDB?

Here is my schema

created_at: {
  type: Date,
  default: Date.now
},
updated_at: {
  type: Date,
  default: Date.now
 }

I need to format my Date.now to HH:MM. It would be great if I could do it before submitting it to the database if thats possible. I need to display that formatted date in a jade file.

This is a node.js application if that helps!

Upvotes: 0

Views: 648

Answers (2)

tauzen
tauzen

Reputation: 76

As damphat pointed out you should store a Date object in the DB and do the formatting in the View. So after retrieving the object from database and before inserting it into your template you should apply a formatting function.

This approach will give you much more flexibility, if in the future you would decide to change the way you present the date in your web app, you will only need to change the formatting function. Sticking to your original idea would require changing each database entry.

I would advise to use moment.js to do the formatting in the View. Just import moment.js and do the following:

var formattedDate = moment(obj.created_at).format("HH:mm");

Upvotes: 2

damphat
damphat

Reputation: 18956

time format should be done in View, not in Model.

If you really want to store time with format you must use type of String instead of Date.

and write your own default function:

function hhmm () {
   var now = new Date();
   return now.getHours() + ':' + now.getMinutes();
}

created_at: {
  type: String,
  default: hhmm
},

Upvotes: 1

Related Questions