最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Moment js format duration - Stack Overflow

programmeradmin0浏览0评论

I got an ISO 8601 string as duration and I need to format it as XhYm( 1h20m). Does anyone have some suggestions?

What I did right now is this:

const duration = moment.duration(secondData.duration);
const formatted = moment.utc(duration.asMilliseconds()).format('HH:mm');

I got an ISO 8601 string as duration and I need to format it as XhYm( 1h20m). Does anyone have some suggestions?

What I did right now is this:

const duration = moment.duration(secondData.duration);
const formatted = moment.utc(duration.asMilliseconds()).format('HH:mm');
Share Improve this question edited Jan 9, 2019 at 14:08 DKyleo 8268 silver badges11 bronze badges asked Jan 9, 2019 at 14:05 user8991667user8991667 952 gold badges2 silver badges7 bronze badges 8
  • maybe this helps stackoverflow.com/questions/11300278/… – David Auvray Commented Jan 9, 2019 at 14:07
  • 3 and what is wrong when you try your code? You didn't make clear. Also please show us the input string from which you want to produce your stated result. – ADyson Commented Jan 9, 2019 at 14:08
  • The input string is PT1H20M and I want to format is as 1h20m, with my code it formats as 01:20 @ADyson – user8991667 Commented Jan 9, 2019 at 14:10
  • 3 link instead of trying to look smart how about you help me :) – user8991667 Commented Jan 9, 2019 at 14:15
  • Actually I'm trying to clarify what you're doing, in order to do exactly that. Ok so it's a duration string, I'm sorry I didn't quite catch that, sorry for misreading. But still, please answer what is secondData and how did you populate it? The example is still incomplete. – ADyson Commented Jan 9, 2019 at 14:15
 |  Show 3 more comments

2 Answers 2

Reset to default 14

To get the output format you want, you'll need to set up the format string differently in the format() call:

const duration = moment.duration('PT1H20M');
const formatted = moment.utc(duration.asMilliseconds()).format("H[h]m[m]");

Using the square brackets makes moment print those characters without trying to use them in the format. See the Escaping Characters in the momentjs documentation.

The simplest way to do it involves a little bit of manual formatting:

var d = moment.duration("PT1H20M");
console.log(d.hours()+"H"+d.minutes()+"M");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论