简体   繁体   English

如何在 node.js 本地更新发布时间

[英]how to update posted time locally in node.js

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这是发布时间未更新的图片我想像 1 分钟前 - 1 小时前 - 1 天前一样定时自动更新

https://i.stack.imgur.com/eTD02.png https://i.stack.imgur.com/eTD02.png

Use momentJS library.使用 momentJS 库。 they have every format you'd need.他们拥有您需要的所有格式。 The one you want is FromNow.你想要的是 FromNow。

It seems like you create "addedDate" once when you run your application using the current time.当您使用当前时间运行您的应用程序时,您似乎创建了一次“addedDate”。 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:在这种情况下,您应该将当前时间添加到您的帖子 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".然后在您的模板中,您将遍历作为“post”传递的 posts 数组,并通过“post.title”和“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.如果您打算显示类似“5 分钟前发布”的内容,那么您可以在模板中创建另一个日期并将其与帖子的“已添加”属性进行比较以找出差异。

The difference can be calculated fairly easily with vanilla JavaScript, you can just subtract two Date objects and get the difference in milliseconds:使用 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;

And so on.等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM