Reputation: 1791
Every item stored in my collection has a createdAt
attribute. I want to query the date in January 24, 2015
format. but when i use {{item.createdAt}}
i get the date in this format Thu Aug 11 2016 22:19:39 GMT+0800 (MYT)
.
Is it possible to get only the name of the month along with the day and the year?
Upvotes: 0
Views: 3459
Reputation: 1128
I recommend using momentjs
package for this. Define a universal helper for the it and sue it across the project.
e.g.
Template.registerHelper('dateFormat', function(context) {
if (window.moment) {
var f = "MM DD YY";
return moment(context).format(f); //had to remove Date(context)
}else{
return context; // moment plugin not available. return data as is.
};
});
When required to format the date, call the function in template using-
{{dateFormat item.createdAt}}
and the date will be formatted.
To add moment package use meteor add momentjs:moment
Upvotes: 1
Reputation: 2650
option 1: control what goes into your collection.
when saving the document you can specify the format of the date instead of simply using the default ISO date you can specify a format such as new Date("<YYYY-mm-dd>")
option 2: use $dateToString to return the date as a formatted string
db.collection.aggregate(
[
{
$project: {
yearMonthDay: { $dateToString: { format: "%Y-%m-%d", date: "$date" } }
}
}
]
)
you can learn more about various formatting options available at - https://docs.mongodb.com/manual/reference/operator/aggregation/dateToString/
option 3: (though you havent specified which programming language you are using)
if i assume you are using node.js then you can read the ISO date from mongodb as-is and then convert it to specific format : dateObject.toLocaleDateString('en-US')
where dataObject is your variable that stores the returned date from the collection.
Upvotes: 0