Skip to content

Lodash - 日期

Lodash 提供了一些与 Date 相关的基本工具函数,主要用于获取当前时间戳(timestamp)。

_.now() 函数返回自 Unix 纪元(1970 年 1 月 1 日 00:00:00 UTC)以来经过的毫秒数,表示当前时间。

_.now()
  • (number): 当前时间戳,以毫秒为单位。

_.now() 在功能上等同于原生 JavaScript 方法 Date.now()。两者返回相同的值。

const lodashTimestamp = _.now();
const nativeTimestamp = Date.now();
console.log(lodashTimestamp); // e.g., 1678886400000
console.log(nativeTimestamp); // e.g., 1678886400000 (likely identical or very close)
console.log(lodashTimestamp === nativeTimestamp); // Typically true, or very close

从历史上看,_.now() 为可能不支持 Date.now() 的旧版 JavaScript 环境提供了兼容性。在现代 JavaScript 环境中,通常更推荐使用原生的 Date.now(),因为它不需要外部库。如果为了保持一致性或针对非常老的环境,你可能仍然会在重度依赖 Lodash 的代码库中看到使用 _.now() 的情况。

// 使用 Node.js (CommonJS)
// const _ = require('lodash');
// 使用 ES Modules
import _ from 'lodash-es';
const startTime = _.now();
// 模拟一些操作
for (let i = 0; i < 1000000; i++) {
// do nothing intensive
}
const endTime = _.now();
const duration = endTime - startTime;
console.log(`Operation started at: ${startTime}`);
console.log(`Operation finished at: ${endTime}`);
console.log(`Operation took ${duration} milliseconds.`);

输出将显示时间戳和模拟操作的持续时间。每次运行代码时,具体的时间戳值都会有所不同。

Lodash 本身不提供广泛的日期格式化、解析或操作功能。对于更复杂的日期/时间需求,可以考虑使用专门的库,例如:

  • Day.js: 一个快速、轻量级的 Moment.js 替代品,具有相似的 API。
  • date-fns: 一个现代的、不可变的、模块化的日期工具库。
  • 原生的 JavaScript Date 对象及其方法(尽管对于复杂任务通常被认为很繁琐)。