How i change my value "created_at" attribute on array map.
this is my object
{ _id: 59661cba54481612500d3043,
author_id: 595e51e0f14cff12e896ead7,
updated_at: 2017-07-12T13:07:52.913Z,
created_at: 2017-12-06T17:00:00.000Z,
trash: false,
tag: [ 595e51e0f14cff12e896ead9, 595e51e0f14cff12e896ead3 ],
category: [ 595e51e0f14cff12e896ead9, 595e51e0f14cff12e896ead3 ],
title: 'test2' }
i want change the value created_at into simple date like this = "13-07-2017"
this is my code
function article(req, res) {
postArticle.find({}, function(err, articles) {
articles.map(function(article) {
var dateCreate = new Date(article.created_at);
var newDate = dateCreate.getDate()+'-' +(dateCreate.getMonth()+1)+'-' +dateCreate.getFullYear();
article.created_at = newDate;
console.log(dateCreate);
console.log(newDate)
console.log(article)
});
// res.render('admin/article/index', {title: 'Article Posts', posts: article})
// res.json({title: 'article', posts: article})
// console.log(article)
})}
but my code doesn't work for changing :(
I have written a method in my project to do this, You can use this code to change the format of date.
function article(req, res) {
postArticle.find({}, function(err, articles) {
articles.map(function(article) {
var dateCreate = formatDate(article.created_at);
var newDate = formatDate(new Date());
article.created_at = newDate;
console.log(dateCreate);
console.log(newDate)
console.log(article)
});
// res.render('admin/article/index', {title: 'Article Posts', posts: article})
// res.json({title: 'article', posts: article})
// console.log(article)
})}
Method to format date:
var formatDate = function (date) {
var myDate = new Date(date);
var y = myDate.getFullYear(),
m = myDate.getMonth() + 1, // january is month 0 in javascript
d = myDate.getDate();
// Get the DD-MM-YYYY format
return formatDigit(d) + "-" + formatDigit(m) + "-" + y;
}
This method will return Month or Day in two digit. Ex. if formatDigit(4) // 04
/**
* Format a month or day in two digit.
*/
var formatDigit = function (val) {
var str = val.toString();
return (str.length < 2) ? "0" + str : str
};
Hope it will work for you.