简体   繁体   English

如何从 Moment.js 持续时间中获取特定日期?

[英]How do I get the specific date from a Moment.js duration?

I'm having trouble understanding how duration works.我无法理解持续时间的工作原理。 To make it simpler to explain consider the following example:为了使解释更简单,请考虑以下示例:

moment.duration(123, 'seconds').humanize()
// => "2 minutes". So far so good

const duration = moment.duration(123123123, 'seconds')
duration.humanize()
// => "4 years". Hmm, I want to know the specific date
duration.format("YYYY/MM/DD")
// => Uncaught TypeError. Well, let's search other solutions
moment.utc(duration.asMilliseconds()).format("YYYY/MM/DD")
// => "1973/11/26". What?! That's not 4 years ago!

So I think I assumed.duration() somehow knows the datetime from X seconds ago, but I suppose it actually just calculates how much seconds is a time equivalent to.所以我想我假设.duration() 不知何故知道 X 秒前的日期时间,但我想它实际上只是计算时间相当于多少秒。 For example, 123 seconds is around 2 minutes, but the function itself doesn't know the time from around 2 minutes ago, which ended up being a bit unintuitive for me to understand.例如,123 秒大约是 2 分钟,但是 function 本身不知道大约 2 分钟前的时间,这对我来说理解起来有点不直观。

That said, I'm not really sure how then I am supposed to translate duration to a date.也就是说,我不确定我应该如何将持续时间转换为日期。 The expected result is whatever date was 123123123 seconds ago.预期结果是 123123123 秒前的任何日期。 How do I achieve that?我如何做到这一点?

Duration is not related to specific dates.持续时间与具体日期无关。 You can use subtract to get the datetime when the duration period started (assuming it ended in this particular moment):您可以使用减法来获取持续时间开始的日期时间(假设它在这个特定时刻结束):

 console.log( moment().subtract(123123123, 'seconds') // your duration.format('MMMM Do YYYY, h:mm:ss a') )
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

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

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