简体   繁体   English

如何使用 moment.js 将日期时间字符串转换为一分钟前/一天前/一个月前/一年前格式

[英]How do I convert a datetime string to a mins ago/day ago/month ago/ year ago format using moment.js

I have a date which is in this format 2020-05-10 22:38:49 coming from my backend API.我有一个格式2020-05-10 22:38:49的日期,来自我的后端 API。 I'm trying to convert this in XXX ago format using moment.js .我正在尝试使用moment.js将其转换为XXX ago格式。 However, the result is always a day ago .然而,结果总是a day ago

 const datetime = moment().utc('2020-05-10 22:38:49').startOf('day').fromNow(); console.log(datetime)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script>

Could anyone please help?有人可以帮忙吗?

It looks like you need to reference moment and call the .utc() method - moment.utc() - as opposed to moment().utc() :看起来您需要参考moment并调用.utc()方法 - moment.utc() - 而不是moment().utc()

 const datetime = moment.utc('2020-05-10 22:38:49').startOf('day').fromNow(); console.log(datetime)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script>

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

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