[英]how to update posted time locally in node.js
我想在用戶創建帖子時更新帖子時間。 我嘗試了一些方法,但沒有得到預期的結果。
注意 - 我將創建的帖子存儲在數組中。 (本地)
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('/');
};
這是發布時間未更新的圖片我想像 1 分鍾前 - 1 小時前 - 1 天前一樣定時自動更新
使用 momentJS 庫。 他們擁有您需要的所有格式。 你想要的是 FromNow。
當您使用當前時間運行您的應用程序時,您似乎創建了一次“addedDate”。 當您顯示新聞提要時,您會傳遞啟動應用程序的分鍾數。
我假設您正在嘗試顯示帖子的創建時間。 在這種情況下,您應該將當前時間添加到您的帖子 object:
exports.postAddPost = (req, res, next) => {
posts.unshift({ title: req.body.title, added: new Date() });
res.redirect('/');
};
然后在您的模板中,您將遍歷作為“post”傳遞的 posts 數組,並通過“post.title”和“post.added”訪問屬性。
我不確定你對會議記錄有什么看法。 如果您打算顯示類似“5 分鍾前發布”的內容,那么您可以在模板中創建另一個日期並將其與帖子的“已添加”屬性進行比較以找出差異。
使用 vanilla JavaScript 可以很容易地計算出差異,您只需減去兩個 Date 對象並獲得以毫秒為單位的差異:
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;
等等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.