I wanna update time for post when user created post. i tried some method but didnt get expected results.
Note - im storing created post in array. (locally)
const posts = [];
const addedDate = new Date();
const addedTime = addedDate.getMinutes();
exports.getIndex = (req, res, next) => {
res.render('index', {
pageTitle: 'NewsFeed',
path: '/',
post: posts,
time: addedTime,
});
};
exports.getPost = (req, res, next) => {
res.render('post', {
pageTitle: 'Create Post',
path: '/post',
});
};
exports.postAddPost = (req, res, next) => {
posts.unshift({ title: req.body.title });
res.redirect('/');
};
Here is the pic of post time is not updating i want to time auto update like 1min ago - 1hr ago - 1 day ago
https://i.stack.imgur.com/eTD02.png
CodePudding user response:
Use momentJS library. they have every format you'd need. The one you want is FromNow.
CodePudding user response:
It seems like you create "addedDate" once when you run your application using the current time. When you show your news feed, you pass along the minutes of the time that you started your application.
I assume that you're trying to display when a post was created. In this case you should add the current time to your post object:
exports.postAddPost = (req, res, next) => {
posts.unshift({ title: req.body.title, added: new Date() });
res.redirect('/');
};
Then in your template you would iterate over the posts array that you pass as "post" and access the properties via "post.title" and "post.added".
I'm not sure what you had in mind regarding the minutes. If you intended to display something like "posted 5 minutes ago", then you could create another Date in your template and compare it with the "added" property of your post to figure out the difference.
The difference can be calculated fairly easily with vanilla JavaScript, you can just subtract two Date objects and get the difference in milliseconds:
const post = {
title: 'Title',
added: new Date(),
};
// some time later
const now = new Date();
const milliseconds = now - post.added;
const seconds = ms / 1000;
const minutes = seconds / 60;
And so on.