英文:
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, '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 -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论