Skip to content

Lodash - Date

Lodash provides a minimal utility function related to Dates, primarily for getting the current timestamp.

The _.now() function retrieves the current time as the number of milliseconds elapsed since the Unix epoch (1 January 1970 00:00:00 UTC).

_.now()
  • (number): The current timestamp in milliseconds.

_.now() is functionally equivalent to the native JavaScript method Date.now(). Both return the same value.

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

Historically, _.now() provided compatibility with older JavaScript environments that might not have supported Date.now(). In modern JavaScript environments, using the native Date.now() is generally preferred as it doesn’t require an external library. You might still see _.now() used in codebases heavily reliant on Lodash for consistency or if targeting very old environments.

// Using Node.js (CommonJS)
// const _ = require('lodash');
// Using ES Modules
import _ from 'lodash-es';
const startTime = _.now();
// Simulate some operation
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.`);

The output will show the timestamps and the duration of the simulated operation. The exact timestamp values will vary each time the code is run.

Lodash itself does not provide extensive date formatting, parsing, or manipulation capabilities. For more complex date/time needs, consider using dedicated libraries like:

  • Day.js: A fast, lightweight alternative to Moment.js with a similar API.
  • date-fns: A modern, immutable, and modular date utility library.
  • The native JavaScript Date object and its methods (though often considered cumbersome for complex tasks).