创建人类可读的时间格式

JavaScriptJavaScriptBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在这个实验中,我们将探索一个名为 formatDuration 的函数,它可以帮助我们将给定的毫秒数转换为人类可读的格式。我们将学习如何使用数学运算来提取天数、小时数、分钟数、秒数和毫秒数的适当值。我们还将使用各种数组方法,如 filtermapjoin,来创建一个以用户友好的方式显示持续时间的字符串。在本实验结束时,你将对如何在 JavaScript 中处理和格式化与时间相关的数据有更深入的理解。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/template_lit("`Template Literals`") subgraph Lab Skills javascript/variables -.-> lab-28316{{"`创建人类可读的时间格式`"}} javascript/data_types -.-> lab-28316{{"`创建人类可读的时间格式`"}} javascript/arith_ops -.-> lab-28316{{"`创建人类可读的时间格式`"}} javascript/comp_ops -.-> lab-28316{{"`创建人类可读的时间格式`"}} javascript/cond_stmts -.-> lab-28316{{"`创建人类可读的时间格式`"}} javascript/array_methods -.-> lab-28316{{"`创建人类可读的时间格式`"}} javascript/higher_funcs -.-> lab-28316{{"`创建人类可读的时间格式`"}} javascript/template_lit -.-> lab-28316{{"`创建人类可读的时间格式`"}} end

格式化持续时间

要获取给定毫秒数的人类可读格式,请执行以下步骤:

  1. 打开终端/SSH 并输入 node 以开始练习编码。
  2. ms 除以适当的值,以获得 小时分钟毫秒 的适当值。
  3. Object.entries()Array.prototype.filter() 一起使用,仅保留非零值。
  4. 使用 Array.prototype.map() 为每个值创建字符串,并适当地使用复数形式。
  5. 使用 Array.prototype.join() 将这些值组合成一个字符串。

以下是代码:

const formatDuration = (ms) => {
  if (ms < 0) ms = -ms;
  const time = {
    day: Math.floor(ms / 86400000),
    hour: Math.floor(ms / 3600000) % 24,
    minute: Math.floor(ms / 60000) % 60,
    second: Math.floor(ms / 1000) % 60,
    millisecond: Math.floor(ms) % 1000
  };
  return Object.entries(time)
    .filter((val) => val[1] !== 0)
    .map(([key, val]) => `${val} ${key}${val !== 1 ? "s" : ""}`)
    .join(", ");
};

以下是一些示例:

formatDuration(1001); // '1 秒, 1 毫秒'
formatDuration(34325055574);
// '397 天, 6 小时, 44 分钟, 15 秒, 574 毫秒'

总结

恭喜你!你已经完成了“格式化持续时间”实验。你可以在 LabEx 中练习更多实验来提升你的技能。

您可能感兴趣的其他 JavaScript 教程