简体   繁体   中英

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. 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.

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. 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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