HumanizeDuration.js 使用教程

HumanizeDuration.js 使用教程

HumanizeDuration.js361000 becomes "6 minutes, 1 second"项目地址:https://gitcode.com/gh_mirrors/hu/HumanizeDuration.js

项目介绍

HumanizeDuration.js 是一个用于将毫秒时间转换为人类可读字符串的 JavaScript 库。这个库可以帮助开发者将时间间隔(以毫秒为单位)转换为易于理解的格式,如“3秒”、“1天3小时2分钟”等。该项目在 GitHub 上开源,由 Evan Hahn 维护。

项目快速启动

安装

你可以通过 npm 安装 HumanizeDuration.js:

npm install humanize-duration

基本使用

在 Node.js 环境中,你可以这样使用:

const humanizeDuration = require('humanize-duration');
console.log(humanizeDuration(3000)); // 输出: "3秒"

在浏览器中,你可以通过引入脚本文件来使用:

<script src="path/to/humanize-duration.js"></script>
<script>
  console.log(humanizeDuration(3000)); // 输出: "3秒"
</script>

应用案例和最佳实践

应用案例

  1. 倒计时显示:在网页或应用中显示倒计时,将剩余时间以人类可读的格式展示给用户。
const timeLeft = 97320000; // 1天3小时2分钟
console.log(humanizeDuration(timeLeft)); // 输出: "1天3小时2分钟"
  1. 日志记录:在日志中记录操作的持续时间,便于后续分析。
const operationDuration = 12345678; // 毫秒
console.log("操作耗时: " + humanizeDuration(operationDuration)); // 输出: "操作耗时: 3小时25分钟45秒"

最佳实践

  1. 多语言支持:HumanizeDuration.js 支持多种语言,可以根据用户偏好设置不同的语言。
const humanize = require('humanize-duration');
const shortEn = humanize.humanizer({
  language: 'shortEn',
  languages: {
    shortEn: {
      y: () => 'y',
      mo: () => 'mo',
      w: () => 'w',
      d: () => 'd',
      h: () => 'h',
      m: () => 'm',
      s: () => 's',
      ms: () => 'ms',
    }
  }
});

console.log(shortEn(3600000)); // 输出: "1h"
  1. 自定义单位:可以根据需要自定义时间单位和格式。
const humanizer = humanizeDuration.humanizer({
  units: ['d', 'h', 'm'],
  round: true
});

console.log(humanizer(97320000)); // 输出: "1天3小时"

典型生态项目

HumanizeDuration.js 可以与其他时间处理库结合使用,例如 Moment.js。以下是一个结合 Moment.js 的示例:

const moment = require('moment');
const humanizeDuration = require('humanize-duration');

const start = moment();
const end = moment().add(1, 'day').add(3, 'hours').add(2, 'minutes');
const duration = moment.duration(end.diff(start));

console.log(humanizeDuration(duration.asMilliseconds())); // 输出: "1天3小时2分钟"

通过结合 Moment.js,可以更灵活地处理和展示时间数据。

HumanizeDuration.js361000 becomes "6 minutes, 1 second"项目地址:https://gitcode.com/gh_mirrors/hu/HumanizeDuration.js

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

石淞畅Oprah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值