<p>JS系で、時間・日時を取り扱うライブラリにdayjsというものがある。(他の有名どころだとMoment.js<sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup>とか)</p> <p><iframe src="https://hatenablog-parts.com/embed?url=https%3A%2F%2Fday.js.org%2F" title="Day.js · 2kB JavaScript date utility library" class="embed-card embed-webcard" scrolling="no" frameborder="0" style="display: block; width: 100%; height: 155px; max-width: 500px; margin: 10px 0px;"></iframe><cite class="hatena-citation"><a href="https://day.js.org/">day.js.org</a></cite> <br></p> <p>ある時、formatを使って秒数を「HH:mm:ss」の形式で表現したくなった。 例えば、144,930秒で表現すると「40:15:30」となる。</p> <p>momentだと上記のようなケースに対応したライブラリがある。</p> <p><a href="https://github.com/jsmreese/moment-duration-format">GitHub - jsmreese/moment-duration-format: Format function plugin for the Moment Duration object.</a></p> <p>momentと似た感じで、 <code>dayjs.duration({ seconds: time }).format('HH:mm:ss') ※timeは任意の秒数</code> でフォーマットできないかと思ったけど、まだdurationでformatは使えないらしい。 ただ、最近devブランチに <code>duration().format</code>を使えるようにしたブランチがマージされたらしいので、これがmasterにマージされれば晴れて上記のようなフォーマットができるようになると思われる。</p> <p><iframe src="https://hatenablog-parts.com/embed?url=https%3A%2F%2Fgithub.com%2Fiamkun%2Fdayjs%2Fissues%2F965" title="How we can format the duration in dayjs. · Issue #965 · iamkun/dayjs" class="embed-card embed-webcard" scrolling="no" frameborder="0" style="display: block; width: 100%; height: 155px; max-width: 500px; margin: 10px 0px;"></iframe><cite class="hatena-citation"><a href="https://github.com/iamkun/dayjs/issues/965">github.com</a></cite></p> <p>ちなみに、dayjs()で生成したものにシンプルにformatを使用しただけだと、24時間ごとに一日とカウントされ、24時間以上のカウントには対応できない。</p> <pre class="code lang-javascript" data-lang="javascript" data-unlink> <span class="synStatement">const</span> time = 144930 * 1000 <span class="synComment">// dayjs(time)のtimeはミリ秒で計算されるため、秒数をミリ秒に変換している</span> dayjs(time).format(<span class="synConstant">'HH:mm:ss'</span>) =&gt; 16:15:30 </pre> <p><br></p> <h4>2021/2/11追記</h4> <p>どうやら上記のような対応の予定は無いらしい。 残念。</p> <p><a href="https://github.com/iamkun/dayjs/issues/1376">Request - Format duration days as more than 24h &middot; Issue #1376 &middot; iamkun/dayjs &middot; GitHub</a></p> <div class="footnotes"> <hr/> <ol> <li id="fn:1"> <p>ただし、Moment.jsは近い将来新しい開発が停止になるそう <iframe src="https://hatenablog-parts.com/embed?url=https%3A%2F%2Fcpoint-lab.co.jp%2Farticle%2F202009%2F17020%2F" title="【JavaScript】Moment.js の新規機能開発が停止。新規プロジェクトへの採用は非推奨へ" class="embed-card embed-webcard" scrolling="no" frameborder="0" style="display: block; width: 100%; height: 155px; max-width: 500px; margin: 10px 0px;"></iframe><cite class="hatena-citation"><a href="https://cpoint-lab.co.jp/article/202009/17020/">cpoint-lab.co.jp</a></cite><a href="#fnref:1" rev="footnote">&#8617;</a></p></li> </ol> </div>