Introduction
Handling dates and times is a common challenge in software development. Whether you're displaying a profile birthdate or a timestamp in a log file, you need a reliable way to manage dates. In this tutorial, we'll explore Day.js in TypeScript for various date formatting tasks.
What is Day.js?
Day.js is a minimalist JavaScript library designed for parsing, validating, manipulating, and displaying dates and times in modern web browsers. With its tiny footprint (around 2KB gzipped), it offers a faster and leaner alternative to other larger date libraries, making it especially suitable for front-end development where performance and speed are crucial.
Its most important features include:
-
Size: One of the standout features of Day.js is its size. It's incredibly lightweight, making it a top choice for projects where minimizing dependencies and load times is a priority.
-
Immutable Operations: Day.js operations do not mutate the original date, ensuring safer date manipulations.
-
Plugin Architecture: Instead of bloating the core library with features, Day.js adopts a plugin-based architecture. This means you only load what you need, keeping things efficient.
-
Locale Support: Day.js supports internationalization and can display dates in various languages and formats, catering to a global audience.
-
Familiar API: If you've worked with other date libraries like Moment.js, transitioning to Day.js is a breeze. Its API is strikingly similar, ensuring a shallow learning curve.
-
Active Community: Day.js has an active community of contributors and is regularly updated, ensuring that it stays compatible with the latest web standards and practices.
Setting Up Your Environment
Before diving into the examples, let's initialize a basic Typescript project.
npm init -y
npm install dayjs
npm install --save-dev typescript ts-node @types/node
npx tsc --init
Day.js format()
The format()
function in Day.js is a versatile tool that allows you to
display dates and times in a variety of patterns. By providing a string of
tokens to this function, you can customize the output to match your desired
format.
Common Format Tokens:
Here's a breakdown of some of the most frequently used format tokens:
-
Year:
YYYY
: 4-digit year (e.g., 2021)YY
: 2-digit year (e.g., 21)
-
Month:
MMMM
: Full month name (e.g., January, February)MMM
: Short month name (e.g., Jan, Feb)MM
: 2-digit month number (e.g., 01, 02)M
: Month number (e.g., 1, 2)
-
Day:
DDDD
: Day of the year (e.g., 001, 365)DD
: 2-digit day of the month (e.g., 01, 31)D
: Day of the month (e.g., 1, 31)dddd
: Full weekday name (e.g., Monday, Tuesday)ddd
: Short weekday name (e.g., Mon, Tue)
-
Hour:
HH
: 2-digit 24-hour format (e.g., 00, 23)H
: 24-hour format (e.g., 0, 23)hh
: 2-digit 12-hour format (e.g., 01, 12)h
: 12-hour format (e.g., 1, 12)
-
Minute:
mm
: 2-digit minutes (e.g., 00, 59)m
: Minutes (e.g., 0, 59)
-
Second:
ss
: 2-digit seconds (e.g., 00, 59)s
: Seconds (e.g., 0, 59)
-
AM/PM:
A
: Uppercase AM or PMa
: Lowercase am or pm
Examples:
Here are some examples to demonstrate the versatility of the format()
function:
const date = dayjs("2021-09-16T14:30:00Z");
// Display date in full format
// Outputs: Saturday, September 16, 2021
console.log(date.format('dddd, MMMM D, YYYY'));
// Display date in compact format
// Outputs: 09/16/21
console.log(date.format('MM/DD/YY'));
// Display time in 12-hour format with AM/PM
// Outputs: 02:30:00 PM
console.log(date.format('hh:mm:ss A'));
// Display time in 24-hour format
// Outputs: 14:30
console.log(date.format('HH:mm'));
Relative Time
Display the difference between two dates in a human-readable format:
import relativeTime from 'dayjs/plugin/relativeTime';
dayjs.extend(relativeTime);
const now = dayjs();
const pastDate = dayjs().subtract(3, 'day');
console.log(now.to(pastDate)); // Outputs: 3 days ago
Custom Date Parsing
Parse custom date formats effortlessly:
const customDate = dayjs("2021-12-04 14:30", "YYYY-MM-DD HH:mm");
console.log(customDate.format("DD/MM/YYYY")); // Outputs: 04/12/2021
Timezone Handling
Manage dates across different time zones:
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(utc);
dayjs.extend(timezone);
const dateInUTC = dayjs.utc("2021-12-04T14:30:00Z");
const dateInNY = dateInUTC.tz('America/New_York');
console.log(dateInNY.format()); // Outputs the date and time in New York's timezone
Duration Formatting
Convert durations into readable formats:
import duration from 'dayjs/plugin/duration';
dayjs.extend(duration);
function formatDuration(milliseconds: number): string {
return dayjs.duration(milliseconds).format("HH:mm:ss");
}
const testDuration = 38114000;
console.log(formatDuration(testDuration)); // Outputs: 10:35:14
Parsing Dates from Various Formats
Day.js can effortlessly parse dates from a multitude of formats:
// Parsing ISO format
// Outputs: 2021-09-16
const isoDate = dayjs("2021-09-16T14:30:00Z");
console.log(isoDate.format('YYYY-MM-DD'));
// Parsing date string without separator
// Outputs: 16/09/2021
const compactDate = dayjs("20210916", "YYYYMMDD");
console.log(compactDate.format('DD/MM/YYYY'));
// Parsing date with textual month
// Outputs: 2021-09-16
const textualDate = dayjs("16 September 2021", "DD MMMM YYYY");
console.log(textualDate.format('YYYY-MM-DD'));
4.6. Formatting Dates with Locale Support
Day.js supports various locales, allowing you to format dates in different languages:
import 'dayjs/locale/fr'; // Import French locale
const date = dayjs("2021-09-16");
// Outputs: samedi, 16 septembre 2021
console.log(date.locale('fr').format('dddd, D MMMM YYYY'));
Advanced Formatting Options
Day.js provides a wide range of formatting tokens for precise date representation:
const date = dayjs("2021-09-16T14:30:00Z");
// Displaying day of the year
// Outputs: 259 (16th September is the 259th day of the year)
console.log(date.format('DDDD'));
// Displaying week of the year
// Outputs: 37 (It's the 37th week of the year)
console.log(date.format('WW'));
// Displaying quarter of the year
// Outputs: 3 (September falls in the third quarter)
console.log(date.format('Q'));
4.8. Unix Timestamps and Day.js
Day.js can parse and format Unix timestamps with ease:
// Parsing Unix timestamp
const unixDate = dayjs.unix(1684563000);
// Outputs the date corresponding to the Unix timestamp
console.log(unixDate.format('YYYY-MM-DD'));
// Converting date to Unix timestamp
// Outputs the Unix timestamp for 16th September 2021
const dateToUnix = dayjs("2021-09-16").unix();
console.log(dateToUnix);
Conclusion Day.js offers a robust solution for all your date formatting needs. Its modular design, combined with a plethora of plugins, ensures that you have all the tools you need for any date-related task. Whether you're formatting dates, calculating durations, or managing time zones, day.js is a library worth adding to your toolkit.