Day.js is a minimalist JavaScript library designed to parse, validate, manipulate, and display dates and times. It’s a lightweight alternative to Moment.js, offering similar functionality but with a significantly smaller footprint. Day.js focuses on providing essential date/time manipulation capabilities without unnecessary bloat, making it ideal for projects where performance and bundle size are critical. It achieves this by utilizing a plugin-based architecture, allowing you to include only the features you actually need.
Lightweight: Day.js is incredibly small, resulting in faster loading times and reduced bundle sizes for your applications. This is a significant advantage over larger libraries like Moment.js.
Easy to use: Its API is intuitive and closely resembles Moment.js, making it easy to learn and adopt, especially if you’re already familiar with Moment.js.
Fast performance: Its optimized code ensures that date and time manipulations are performed efficiently.
Plugin-based architecture: Allows you to include only the features you need, minimizing the overall size of your application. This reduces the download time and improves performance further.
Active community and maintainance: Day.js has a thriving community and is actively maintained, ensuring ongoing support and updates.
Day.js can be installed using various package managers:
npm:
npm install dayjs
yarn:
yarn add dayjs
CDN: Include the Day.js script directly in your HTML:
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
For specific plugins, install them separately and import them after Day.js (see plugin documentation for specific instructions).
After installing Day.js, you can start using it immediately. Here’s a basic example:
import dayjs from 'dayjs';
// Create a Day.js object from the current date and time
const now = dayjs();
console.log(now); // Outputs the current date and time
// Create a Day.js object from a specific date string
const date = dayjs('2024-03-15');
console.log(date); // Outputs the specified date
// Format the date
const formattedDate = date.format('YYYY-MM-DD');
console.log(formattedDate); // Outputs '2024-03-15'
// Add days to the date
const futureDate = date.add(7, 'day');
console.log(futureDate); // Outputs the date 7 days after 2024-03-15
// Subtract days from the date
const pastDate = date.subtract(3, 'month');
console.log(pastDate); // Outputs the date 3 months before 2024-03-15
//Difference between two dates
const diff = dayjs().diff(date, 'day'); // difference in days from date to now
console.log(diff);
This is just a starting point. Refer to the API documentation for a comprehensive list of available methods and functionalities. Remember to consult the documentation for any plugins you choose to use, as their import and usage may vary.
Day.js offers versatile parsing capabilities, allowing you to create Day.js objects from various input formats.
Day.js intelligently parses a wide range of date string formats. It attempts to understand the format based on the input, making it highly flexible.
import dayjs from 'dayjs';
const date1 = dayjs('2024-10-26'); // ISO 8601 format
const date2 = dayjs('10/26/2024'); // MM/DD/YYYY format (US common)
const date3 = dayjs('October 26, 2024'); // Month Name, Day, Year format
const date4 = dayjs('26 Oct 2024'); // DD Mon YYYY format
console.log(date1.format('YYYY-MM-DD')); // Output: 2024-10-26
console.log(date2.format('YYYY-MM-DD')); // Output: 2024-10-26
console.log(date3.format('YYYY-MM-DD')); // Output: 2024-10-26
console.log(date4.format('YYYY-MM-DD')); // Output: 2024-10-26
//Invalid Date
const invalidDate = dayjs('2024-13-26')
console.log(invalidDate.isValid()) //Output: false
While Day.js is quite tolerant, it might misinterpret ambiguous strings. For better control, use custom parsers or specify a format (see below).
Unix timestamps (seconds or milliseconds since the Unix epoch) are easily parsed:
import dayjs from 'dayjs';
const timestampInSeconds = 1700000000;
const dateFromSeconds = dayjs.unix(timestampInSeconds);
console.log(dateFromSeconds.format('YYYY-MM-DD HH:mm:ss'));
const timestampInMilliseconds = 1700000000000;
const dateFromMilliseconds = dayjs(timestampInMilliseconds); // dayjs handles milliseconds automatically
console.log(dateFromMilliseconds.format('YYYY-MM-DD HH:mm:ss'));
You can create a Day.js object from a native JavaScript Date
object:
import dayjs from 'dayjs';
const jsDate = new Date();
const dayjsDate = dayjs(jsDate);
console.log(dayjsDate.format('YYYY-MM-DD HH:mm:ss'));
For complex or unusual date formats, you can create custom parsing functions using dayjs.extend
and dayjs.parse
. This is advanced usage and generally not needed for common formats. Refer to the Day.js documentation for detailed examples on creating custom parsers.
To ensure precise parsing, especially with ambiguous date strings, you can specify the expected format using dayjs(String, Format)
:
import dayjs from 'dayjs';
//If your input is always in MM/DD/YYYY format
const date = dayjs('10/26/2024', 'MM/DD/YYYY');
console.log(date.format('YYYY-MM-DD')); //Output: 2024-10-26
//If your input is always in DD MMM YYYY format
const date2 = dayjs('26 Oct 2024', 'DD MMM YYYY');
console.log(date2.format('YYYY-MM-DD')); // Output: 2024-10-26
Using a format string guarantees that Day.js interprets the date correctly, preventing potential misinterpretations. Refer to the Day.js documentation for the format string syntax.
Day.js provides powerful tools for formatting and displaying dates in various ways.
The primary method for formatting dates is format()
. It accepts a format string as an argument, specifying how the date should be displayed.
import dayjs from 'dayjs';
const date = dayjs('2024-10-27');
// Common formats
console.log(date.format('YYYY-MM-DD')); // 2024-10-27
console.log(date.format('MMMM D, YYYY')); // October 27, 2024
console.log(date.format('ddd, MMM D')); // Sun, Oct 27
console.log(date.format('h:mm A')); // 12:00 AM (assuming the time is midnight)
console.log(date.format('HH:mm')); // 00:00
//More complex format examples
console.log(date.format('YYYY [escaped] YYYY')); // 2024 escaped 2024
console.log(date.format('YYYY MMM DD HH:mm:ss')); // 2024 Oct 27 00:00:00
Refer to the Day.js documentation for a complete list of formatting tokens.
While Day.js provides numerous predefined tokens, you can extend its formatting capabilities by defining custom tokens using dayjs.extend
. This is an advanced feature generally not required for common formatting needs. Refer to Day.js documentation for details on extending its functionality.
Day.js supports internationalization through locales. By default, it uses the English locale. To use a different locale, you need to install the corresponding locale plugin and load it:
import dayjs from 'dayjs';
import 'dayjs/locale/es'; //Example Spanish locale
.locale('es'); // set locale
dayjs
const date = dayjs();
console.log(date.format('MMMM D, YYYY')); // Output will be in Spanish
You’ll need to install the specific locale you need (e.g., dayjs/locale/fr
for French). Many locales are available; consult the Day.js documentation for a list and installation instructions.
Day.js provides methods for displaying time differences in a human-readable format (e.g., “a few seconds ago,” “2 days ago”). The fromNow()
method is commonly used for this:
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime'
.extend(relativeTime)
dayjs
const date = dayjs('2024-10-26');
console.log(date.fromNow()); // Output (will vary based on current time): "in 1 day", "a day ago", etc.
const date2 = dayjs().subtract(2, 'hour');
console.log(date2.fromNow()); //Output: a few hours ago
Remember to install the dayjs/plugin/relativeTime
plugin.
Day.js’s core functionality does not include built-in time zone support. To work with time zones, you need to utilize a plugin, such as dayjs-timezone
. After installing the plugin, you can use it to parse and display dates with time zone information:
//Requires installing dayjs-timezone: npm install dayjs dayjs-timezone
import dayjs from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
.extend(utc);
dayjs.extend(timezone);
dayjs
.tz.setDefault('America/New_York'); // Set default timezone
dayjs
const date = dayjs('2024-10-27 10:00', 'YYYY-MM-DD HH:mm');
console.log(date.tz().format()); //Output will show the date and time in the specified timezone
const dateInLondon = dayjs('2024-10-27 10:00', 'YYYY-MM-DD HH:mm').tz('Europe/London');
console.log(dateInLondon.format()); //Output in London's timezone
Remember to install the necessary plugins (dayjs-timezone
). Proper time zone handling requires careful consideration of your application’s needs and the capabilities of the chosen plugin.
Day.js provides a comprehensive set of methods for manipulating dates and times.
You can add or subtract units of time (days, months, years, hours, minutes, seconds, etc.) using the add()
and subtract()
methods.
import dayjs from 'dayjs';
const date = dayjs('2024-10-27');
// Adding time
const futureDate = date.add(5, 'day'); // Add 5 days
console.log(futureDate.format('YYYY-MM-DD')); // Output: 2024-11-01
const futureDate2 = date.add(2, 'month'); //Add 2 Months
console.log(futureDate2.format('YYYY-MM-DD')); //Output: 2024-12-27
const futureDate3 = date.add(1, 'year'); //Add 1 year
console.log(futureDate3.format('YYYY-MM-DD')); //Output: 2025-10-27
// Subtracting time
const pastDate = date.subtract(2, 'week'); // Subtract 2 weeks
console.log(pastDate.format('YYYY-MM-DD')); // Output: 2024-10-13
const pastDate2 = date.subtract(1,'hour'); //Subtract 1 hour
console.log(pastDate2.format('YYYY-MM-DD HH:mm')); //Output will show the time 1 hour before
You can add/subtract various units like day
, month
, year
, hour
, minute
, second
, etc.
You can extract individual components of a date using various methods:
import dayjs from 'dayjs';
const date = dayjs('2024-10-27 14:30:00');
console.log(date.year()); // 2024
console.log(date.month()); // 9 (months are 0-indexed)
console.log(date.date()); // 27
console.log(date.day()); // 0 (Sunday is 0)
console.log(date.hour()); // 14
console.log(date.minute()); // 30
console.log(date.second()); // 0
console.log(date.millisecond()); // 0
console.log(date.dayOfYear()); // Day of the year (1-366)
console.log(date.week()); // Week of the year (1-52 or 53)
You can modify individual date components using set()
and related methods:
import dayjs from 'dayjs';
let date = dayjs('2024-10-27');
= date.set('year', 2025);
date console.log(date.format('YYYY-MM-DD')); // Output: 2025-10-27
= date.set('month', 11); //Sets the month to December (11 is December because months are 0-indexed)
date console.log(date.format('YYYY-MM-DD')); // Output: 2025-12-27
= date.set('date', 1); //Sets the day to the 1st of the month
date console.log(date.format('YYYY-MM-DD')); //Output: 2025-12-01
= date.set('hour', 10); //Sets the hour to 10
date console.log(date.format('YYYY-MM-DD HH:mm')); //Output will show the time with the hour changed
Day.js provides methods to get the start and end of various time periods:
import dayjs from 'dayjs';
const date = dayjs('2024-10-27');
console.log(date.startOf('day').format('YYYY-MM-DD HH:mm:ss')); //Start of the day
console.log(date.endOf('day').format('YYYY-MM-DD HH:mm:ss')); //End of the day
console.log(date.startOf('month').format('YYYY-MM-DD')); //Start of the month
console.log(date.endOf('month').format('YYYY-MM-DD')); //End of the month
console.log(date.startOf('year').format('YYYY-MM-DD')); //Start of the year
console.log(date.endOf('year').format('YYYY-MM-DD')); //End of the year
console.log(date.startOf('week').format('YYYY-MM-DD')); //Start of the week (depends on locale's first day of week)
console.log(date.endOf('week').format('YYYY-MM-DD')); //End of the week
You can compare dates using standard comparison operators:
import dayjs from 'dayjs';
const date1 = dayjs('2024-10-26');
const date2 = dayjs('2024-10-27');
console.log(date1 < date2); // true
console.log(date1 > date2); // false
console.log(date1 <= date2); // true
console.log(date1 >= date2); // false
console.log(date1.isSame(date2)); // false
console.log(date1.isSame(dayjs('2024-10-26'))); //true - checks for same date, not just comparison
The isSame()
method provides a more robust comparison, considering the precision you specify (e.g., isSame(date2, 'day')
checks if the dates are the same day).
The diff()
method calculates the difference between two dates in specified units:
import dayjs from 'dayjs';
const date1 = dayjs('2024-10-26');
const date2 = dayjs('2024-11-01');
console.log(date2.diff(date1, 'day')); // 5 (difference in days)
console.log(date2.diff(date1, 'month')); // 0 (difference in months - note that it is only the difference in full months)
console.log(date2.diff(date1, 'year')); // 0 (difference in years)
console.log(date2.diff(date1, 'hour')); //120 (difference in hours)
The second argument specifies the unit of the difference (day
, month
, year
, hour
, minute
, second
, etc.). Note that the difference calculation for months and years might not always align perfectly with calendar conventions.
This section covers advanced techniques and considerations for working with Day.js.
Day.js’s plugin architecture is a key strength, allowing you to extend its functionality without bloating the core library. Creating a plugin involves creating a function that extends Day.js’s prototype.
Example Plugin (Adding a isLeapYear()
method):
// my-leap-year-plugin.js
export default function (dayjs) {
.extend((dayjs) => {
dayjs.prototype.isLeapYear = function () {
dayjsconst year = this.year();
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
;
};
}) }
Using the Plugin:
import dayjs from 'dayjs';
import leapYearPlugin from './my-leap-year-plugin'; // Path to your plugin
.extend(leapYearPlugin);
dayjs
const date = dayjs('2024-01-01');
console.log(date.isLeapYear()); // true
const date2 = dayjs('2023-01-01');
console.log(date2.isLeapYear()); // false
Remember to export the plugin function and import it into your main application.
While plugins are the recommended approach for extending functionality, you can directly extend Day.js’s prototype if absolutely necessary. However, this is less maintainable than using plugins and could lead to conflicts if multiple extensions modify the same prototype methods. Use this approach with caution.
Example (Direct Prototype Extension - AVOID unless absolutely necessary):
import dayjs from 'dayjs';
.prototype.myCustomMethod = function() {
dayjs// Your custom method logic here...
return this.format('YYYYMMDD') + 'custom';
;
}
const date = dayjs();
console.log(date.myCustomMethod());
Day.js’s core doesn’t inherently support calendars beyond the Gregorian calendar. To work with other calendars (e.g., Hijri, Buddhist), you’ll need to use a dedicated plugin designed for that calendar system. These plugins typically provide custom parsing, formatting, and manipulation methods specific to the target calendar.
For optimal performance, especially in applications with many date manipulations:
valueOf()
: If you need to compare dates for equality, the valueOf()
method often offers faster comparison than comparing formatted strings.Day.js integrates well with other JavaScript libraries and frameworks. Its simple API makes it easy to incorporate into existing projects.
Remember to always consult the Day.js documentation and the documentation of any plugins you use for the most up-to-date information and best practices.
Day.js provides several utility functions beyond core date manipulation.
While Day.js doesn’t have a dedicated Duration
object like Moment.js, you can achieve similar functionality by using the diff()
method and calculating durations yourself.
import dayjs from 'dayjs';
const startDate = dayjs('2024-10-26');
const endDate = dayjs('2024-11-05');
const diffDays = endDate.diff(startDate, 'day');
const diffMonths = endDate.diff(startDate, 'month'); //Note: this might not always reflect calendar months perfectly.
console.log(`Difference: ${diffDays} days`);
console.log(`Difference (approximate): ${diffMonths} months`);
// For more precise duration calculations (hours, minutes, seconds), you would need to calculate them individually using diff
const diffHours = endDate.diff(startDate, 'hour');
const diffMinutes = endDate.diff(startDate, 'minute');
const diffSeconds = endDate.diff(startDate, 'second');
console.log(`Difference: ${diffHours} hours, ${diffMinutes} minutes, ${diffSeconds} seconds`)
For complex duration calculations or formatting, creating a custom helper function is recommended.
The isValid()
method checks if a Day.js object represents a valid date:
import dayjs from 'dayjs';
const validDate = dayjs('2024-10-27');
const invalidDate = dayjs('2024-13-27'); // Invalid month
console.log(validDate.isValid()); // true
console.log(invalidDate.isValid()); // false
This is useful for error handling and validating user inputs.
Day.js doesn’t have a large collection of independent helper functions like some other date libraries. Its strength lies in its core date manipulation and formatting methods. If you need extra utility functions, it’s generally best to create them yourself or use a plugin if the function is broadly useful and reusable.
Day.js and Moment.js share a similar API, making it relatively easy to switch between them. However, there are key differences:
Feature | Day.js | Moment.js |
---|---|---|
Size | Significantly smaller | Much larger |
Performance | Generally faster | Can be slower, especially with many dates |
Timezone Support | Requires a plugin (dayjs-timezone) | Built-in (but can be complex) |
Locale Support | Requires plugins for locales | Built-in support for many locales |
Features | Core functionality; extend with plugins | Extensive built-in features |
Build System | Simpler | More complex |
Day.js prioritizes a small footprint and fast performance, while Moment.js offers a wider range of features out-of-the-box. The choice depends on your project’s specific needs and priorities. If you need a lightweight library with essential date/time functionality, Day.js is a strong contender. If you require many features directly included in the library and bundle size is less critical, Moment.js might be a better fit. However, the smaller size and improved performance of Day.js often outweigh the need for a more comprehensive feature set directly within the library.
We welcome contributions to Day.js! Whether you find a bug, have a feature request, or want to improve the codebase, your help is valuable.
If you encounter a bug or have a feature request, please follow these steps:
If you’d like to contribute code, please follow these guidelines:
fix-bug-invalid-date-parsing
, feat-add-new-locale
).fix: correct invalid date parsing
).Day.js follows a consistent coding style to ensure readability and maintainability. Please adhere to these guidelines when contributing code:
By following these guidelines, you’ll help ensure that your contributions are easily integrated into the Day.js project and maintain the high quality of the library. The maintainers of the project will review your changes before merging them into the main codebase. Remember to be patient and responsive to feedback during the review process.
This appendix provides supplementary information for working with Day.js.
Day.js uses a wide range of formatting tokens to customize date/time output. Here’s a partial list; refer to the official Day.js documentation for the most comprehensive list. Remember that the exact output for some tokens may depend on the locale.
Token | Description | Example Output |
---|---|---|
YYYY |
Year (4 digits) | 2024 |
YY |
Year (2 digits) | 24 |
MMMM |
Month name (long) | October |
MMM |
Month name (short) | Oct |
MM |
Month (2 digits) | 10 |
M |
Month (1 or 2 digits) | 10 |
DD |
Day of month (2 digits) | 27 |
D |
Day of month (1 or 2 digits) | 27 |
ddd |
Day of week (short) | Sun |
dddd |
Day of week (long) | Sunday |
d |
Day of week (1-7, Sunday=0) | 0 |
HH |
Hour (24-hour clock) | 14 |
H |
Hour (24-hour clock) | 14 |
hh |
Hour (12-hour clock) | 02 |
h |
Hour (12-hour clock) | 2 |
mm |
Minute (2 digits) | 30 |
m |
Minute (1 or 2 digits) | 30 |
ss |
Second (2 digits) | 45 |
s |
Second (1 or 2 digits) | 45 |
SSS |
Millisecond (3 digits) | 123 |
A |
AM/PM | PM |
a |
am/pm | pm |
Z |
Timezone offset | +00:00 |
ZZ |
Timezone offset (short) | +00 |
isValid()
returns false
, check your date string format and ensure it’s compatible with Day.js parsing rules. Use explicit format strings if necessary.dayjs-timezone
plugin and configured it correctly. Double-check the timezone identifier you’re using.dayjs.locale()
.If you continue to experience issues, consult the Day.js GitHub issues and the community forums for potential solutions. If you find a bug, please report it following the guidelines in the Contributing section.