如何使用moment.js将0.5个月和1.5个月分别转换为2周和6周?

huangapple go评论69阅读模式
英文:

How can I convert 0.5 months and 1.5 months to 2 weeks and 6 weeks respectively using moment.js?

问题

如何使用moment.js将0.5个月和1.5个月分别转换为2周和6周?

我正在使用一个API,其中一些对象属性以月为单位,并且我想将分数月份显示为周,而保留完整的月份数字。这是否可以使用moment.js的duration()实现?

英文:

How can I convert 0.5 months and 1.5 months to 2 weeks and 6 weeks respectively using moment.js?

I am consuming an API which has some object properties in units of months and I want to show fractional months in weeks where as keep the full numbers in months. Is this achievable using moment.js duration()?

答案1

得分: 1

你应该能够使用 moment 的 duration 来解决这个问题。

moment.duration({'months' : 0.5}).asWeeks();

请记住,你需要根据需要四舍五入输出,因为在上面的示例中,输出将是 2.142857142857143。

这是我使用 moment.js 来处理这个问题的方式,但是否这真的是你寻找的东西是另一个问题。

moment.js 持续时间的文档 在此

英文:

You should be able to solve this using moment's duration.

moment.duration({'months' : 0.5}).asWeeks();

Keep in mind that you'll have to round the output as you see fit, as in the above example the output will be 2.142857142857143.

This is how I'd approach this using moment.js but whether this is really what you're looking for is another question.

Documentation for moment.js durations here

答案2

得分: 0

以下是翻译好的部分:

The other answer appears to be much better, but logically this is how I tried to tackle the problem:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    var d = moment.duration(0.5, 'months')
    var start = moment('01-01-2020')
    var end = moment('01-01-2020').add(d.asSeconds(), 'seconds')
    var now = end.diff(start, "week")

    console.log(now) // 2

<!-- language: lang-html -->

    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>


<!-- end snippet -->
英文:

The other answer appears to be much better, but logically this is how I tried to tackle the problem:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var d = moment.duration(0.5, &#39;months&#39;)
var start = moment(&#39;01-01-2020&#39;)
var end = moment(&#39;01-01-2020&#39;).add(d.asSeconds(), &#39;seconds&#39;)
var now = end.diff(start, &quot;week&quot;)

console.log(now) // 2

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年1月7日 00:43:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定