Logo
⚠️ Unsaved
[M]:

Working with Dates in JavaScript Using date-fns

This notebook demonstrates how to use the popular date-fns library to handle date operations in JavaScript. The date-fns library provides a comprehensive, consistent, and immutable toolset for manipulating JavaScript dates.

[1]:
!npm install date-fns
$ npm install date-fns

added 1 package in 2s

29 packages are looking for funding
  run `npm fund` for details
[2]:
// First, let's import the date-fns library
// In a real project, you would install it using: npm install date-fns
// For this notebook, we'll use a CDN
import * as dateFns from 'date-fns';

// Let's check if the library is loaded correctly
console.log("date-fns version:", dateFns.version, "\n");

// Create a sample date to work with
const today = new Date();
console.log("Current date:", today.toString(), "\n");
console.log("Native JavaScript date format:", today.toISOString(), "\n");
date-fns version: undefined 
Current date: Wed Mar 19 2025 13:48:52 GMT+0000 (Western European Standard Time) 
Native JavaScript date format: 2025-03-19T13:48:52.196Z 
[M]:

1. Basic Date Formatting

One of the most common tasks when working with dates is formatting them for display. The date-fns library provides a powerful format function for this purpose.

[3]:
// Basic date formatting examples
console.log("Basic date formatting examples:\n");

// Format as MM/DD/YYYY
console.log("MM/DD/YYYY:", dateFns.format(today, 'MM/dd/yyyy'), "\n");

// Format as Month Day, Year
console.log("Month Day, Year:", dateFns.format(today, 'MMMM d, yyyy'), "\n");

// Format with day of week
console.log("Day of week:", dateFns.format(today, 'EEEE, MMMM d, yyyy'), "\n");

// Format with time
console.log("With time (12-hour):", dateFns.format(today, 'MMMM d, yyyy h:mm a'), "\n");
console.log("With time (24-hour):", dateFns.format(today, 'yyyy-MM-dd HH:mm:ss'), "\n");

// ISO 8601 format
console.log("ISO 8601:", dateFns.formatISO(today), "\n");

// RFC 2822 format
console.log("RFC 2822:", dateFns.formatRFC2822(today), "\n");

// Relative time (e.g., "2 hours ago")
const twoHoursAgo = dateFns.subHours(today, 2);
console.log("Relative time:", dateFns.formatDistanceToNow(twoHoursAgo), "ago\n");
Error during execution: dateFns.formatRFC2822 is not a functionBasic date formatting examples: MM/DD/YYYY: 03/19/2025 Month Day, Year: March 19, 2025 Day of week: Wednesday, March 19, 2025 With time (12-hour): March 19, 2025 1:48 PM With time (24-hour): 2025-03-19 13:48:52 ISO 8601: 2025-03-19T13:48:52Z
[M]:

2. Date Arithmetic

The date-fns library makes it easy to perform date arithmetic operations like adding or subtracting days, months, years, etc.

[4]:
// Date arithmetic examples
console.log("Date arithmetic examples:\n");

// Add 5 days to today
const fiveDaysLater = dateFns.addDays(today, 5);
console.log("5 days from now:", dateFns.format(fiveDaysLater, 'MMMM d, yyyy'), "\n");

// Subtract 1 week from today
const lastWeek = dateFns.subWeeks(today, 1);
console.log("1 week ago:", dateFns.format(lastWeek, 'MMMM d, yyyy'), "\n");

// Add 3 months to today
const threeMonthsLater = dateFns.addMonths(today, 3);
console.log("3 months from now:", dateFns.format(threeMonthsLater, 'MMMM d, yyyy'), "\n");

// Add 1 year and subtract 2 days
const nextYearMinusTwoDays = dateFns.subDays(dateFns.addYears(today, 1), 2);
console.log("1 year from now minus 2 days:", dateFns.format(nextYearMinusTwoDays, 'MMMM d, yyyy'), "\n");

// Get the first day of the current month
const firstDayOfMonth = dateFns.startOfMonth(today);
console.log("First day of current month:", dateFns.format(firstDayOfMonth, 'MMMM d, yyyy'), "\n");

// Get the last day of the current month
const lastDayOfMonth = dateFns.endOfMonth(today);
console.log("Last day of current month:", dateFns.format(lastDayOfMonth, 'MMMM d, yyyy'), "\n");
Date arithmetic examples:
5 days from now: March 24, 2025 
1 week ago: March 12, 2025 
3 months from now: June 19, 2025 
1 year from now minus 2 days: March 17, 2026 
First day of current month: March 1, 2025 
Last day of current month: March 31, 2025 
[M]:

3. Date Comparisons

The date-fns library provides various functions for comparing dates.

[5]:
// Date comparison examples
console.log("Date comparison examples:\n");

const date1 = new Date(2023, 0, 15); // January 15, 2023
const date2 = new Date(2023, 0, 20); // January 20, 2023

// Check if date1 is before date2
console.log("Is date1 before date2?", dateFns.isBefore(date1, date2), "\n");

// Check if date2 is after date1
console.log("Is date2 after date1?", dateFns.isAfter(date2, date1), "\n");

// Check if two dates are the same
const sameDate = new Date(2023, 0, 15);
console.log("Are date1 and sameDate the same?", dateFns.isSameDay(date1, sameDate), "\n");

// Check if a date is today
console.log("Is today today?", dateFns.isToday(today), "\n");
console.log("Is date1 today?", dateFns.isToday(date1), "\n");

// Check if a date is in the past
console.log("Is date1 in the past?", dateFns.isPast(date1), "\n");

// Check if a date is in the future
const futureDate = dateFns.addYears(today, 1);
console.log("Is futureDate in the future?", dateFns.isFuture(futureDate), "\n");

// Calculate the difference between two dates
const diffInDays = dateFns.differenceInDays(date2, date1);
console.log("Difference between date2 and date1 in days:", diffInDays, "\n");

const diffInMonths = dateFns.differenceInMonths(futureDate, today);
console.log("Difference between futureDate and today in months:", diffInMonths, "\n");
Date comparison examples:
Is date1 before date2? true 
Is date2 after date1? true 
Are date1 and sameDate the same? true 
Is today today? true 
Is date1 today? false 
Is date1 in the past? true 
Is futureDate in the future? true 
Difference between date2 and date1 in days: 5 
Difference between futureDate and today in months: 12 
[M]:

4. Working with Date Ranges

The date-fns library provides functions for working with date ranges.

[6]:
// Date range examples
console.log("Date range examples:\n");

// Check if a date is within a range
const startDate = new Date(2023, 0, 1); // January 1, 2023
const endDate = new Date(2023, 11, 31); // December 31, 2023
const testDate = new Date(2023, 6, 15); // July 15, 2023

const isWithinRange = dateFns.isWithinInterval(testDate, { start: startDate, end: endDate });
console.log("Is testDate within the range?", isWithinRange, "\n");

// Get all days in a month
const year = 2023;
const month = 1; // February (0-indexed)
const daysInMonth = dateFns.getDaysInMonth(new Date(year, month));
console.log(`Number of days in February ${year}:`, daysInMonth, "\n");

// Generate an array of dates for a week
const weekStart = dateFns.startOfWeek(today);
const weekDates = Array.from({ length: 7 }, (_, i) => dateFns.addDays(weekStart, i));

console.log("Dates for this week:\n");
weekDates.forEach(date => {
console.log(dateFns.format(date, 'EEEE, MMMM d, yyyy'), "\n");
});

// Check if a year is a leap year
console.log(`Is ${year} a leap year?`, dateFns.isLeapYear(new Date(year, 0, 1)), "\n");
Date range examples:
Is testDate within the range? true 
Number of days in February 2023: 28 
Dates for this week:
Sunday, March 16, 2025 
Monday, March 17, 2025 
Tuesday, March 18, 2025 
Wednesday, March 19, 2025 
Thursday, March 20, 2025 
Friday, March 21, 2025 
Saturday, March 22, 2025 
Is 2023 a leap year? false 
[M]:

5. Parsing Dates

The date-fns library provides functions for parsing date strings into JavaScript Date objects.

[7]:
// Date parsing examples
console.log("Date parsing examples:\n");

// Parse a date string with a specific format
const dateStr1 = "2023-03-15";
const parsedDate1 = dateFns.parse(dateStr1, 'yyyy-MM-dd', new Date());
console.log(`Parsed '${dateStr1}':`, dateFns.format(parsedDate1, 'MMMM d, yyyy'), "\n");

// Parse a date string with a different format
const dateStr2 = "15/03/2023";
const parsedDate2 = dateFns.parse(dateStr2, 'dd/MM/yyyy', new Date());
console.log(`Parsed '${dateStr2}':`, dateFns.format(parsedDate2, 'MMMM d, yyyy'), "\n");

// Parse an ISO date string
const isoDateStr = "2023-03-15T14:30:45.123Z";
const parsedIsoDate = dateFns.parseISO(isoDateStr);
console.log(`Parsed ISO date '${isoDateStr}':`, dateFns.format(parsedIsoDate, 'MMMM d, yyyy HH:mm:ss'), "\n");

// Parse a Unix timestamp (in milliseconds)
const timestamp = 1678888888888; // March 15, 2023, approximately
const dateFromTimestamp = dateFns.fromUnixTime(timestamp / 1000); // fromUnixTime expects seconds
console.log(`Date from timestamp ${timestamp}:`, dateFns.format(dateFromTimestamp, 'MMMM d, yyyy HH:mm:ss'), "\n");
Date parsing examples:
Parsed '2023-03-15': March 15, 2023 
Parsed '15/03/2023': March 15, 2023 
Parsed ISO date '2023-03-15T14:30:45.123Z': March 15, 2023 14:30:45 
Date from timestamp 1678888888888: March 15, 2023 14:01:28 
[M]:

6. Timezone Handling

The date-fns-tz extension provides timezone support for date-fns.

[8]:
// For timezone support, we need date-fns-tz
import * as dateFnsTz from 'https://cdn.skypack.dev/date-fns-tz';

// Timezone examples
console.log("Timezone examples:\n");

// Get the current date in a specific timezone
const nyDate = dateFnsTz.zonedTimeToUtc(today, 'America/New_York');
console.log("Current date in New York:", dateFns.format(nyDate, 'yyyy-MM-dd HH:mm:ss'), "\n");

// Format a date for a specific timezone
const tokyoTime = dateFnsTz.format(
dateFnsTz.utcToZonedTime(today, 'Asia/Tokyo'),
'yyyy-MM-dd HH:mm:ss zzz',
{ timeZone: 'Asia/Tokyo' }
);
console.log("Current date in Tokyo:", tokyoTime, "\n");

// Convert between timezones
const sydneyTime = dateFnsTz.format(
dateFnsTz.utcToZonedTime(today, 'Australia/Sydney'),
'yyyy-MM-dd HH:mm:ss zzz',
{ timeZone: 'Australia/Sydney' }
);
console.log("Current date in Sydney:", sydneyTime, "\n");

// Get the timezone offset
const nyOffset = dateFnsTz.getTimezoneOffset('America/New_York', today);
console.log("New York timezone offset (in minutes):", nyOffset / 60000, "\n"); // Convert ms to minutes
Error during execution: Cannot find module 'https://cdn.skypack.dev/date-fns-tz' Require stack: - /home/bfwsdlnpboac0izci3s7i3zj938f6s-jbm1/watcher.js
[M]:

7. Practical Examples

Let's look at some practical examples of using date-fns in real-world scenarios.

[9]:
// Practical example 1: Date validation
console.log("Practical example 1: Date validation\n");

function isValidDateFormat(dateStr, format) {
const parsedDate = dateFns.parse(dateStr, format, new Date());
return dateFns.isValid(parsedDate);
}

const validDateStr = "2023-04-15";
const invalidDateStr = "2023-04-32"; // April has only 30 days

console.log(`Is '${validDateStr}' a valid date? ${isValidDateFormat(validDateStr, 'yyyy-MM-dd')}\n`);
console.log(`Is '${invalidDateStr}' a valid date? ${isValidDateFormat(invalidDateStr, 'yyyy-MM-dd')}\n`);

// Practical example 2: Age calculation
console.log("Practical example 2: Age calculation\n");

function calculateAge(birthDate) {
return dateFns.differenceInYears(new Date(), birthDate);
}

const birthDate = new Date(1990, 5, 15); // June 15, 1990
console.log(`Age of someone born on ${dateFns.format(birthDate, 'MMMM d, yyyy')}: ${calculateAge(birthDate)} years\n`);

// Practical example 3: Business days calculation
console.log("Practical example 3: Business days calculation\n");

function addBusinessDays(startDate, days) {
return dateFns.addBusinessDays(startDate, days);
}

const startDate = new Date(2023, 3, 10); // April 10, 2023
const deliveryDate = addBusinessDays(startDate, 5); // Add 5 business days

console.log(`Order date: ${dateFns.format(startDate, 'MMMM d, yyyy')}\n`);
console.log(`Estimated delivery date (5 business days later): ${dateFns.format(deliveryDate, 'MMMM d, yyyy')}\n`);
Practical example 1: Date validation
Is '2023-04-15' a valid date? true
Is '2023-04-32' a valid date? false
Practical example 2: Age calculation
Age of someone born on June 15, 1990: 34 years
Practical example 3: Business days calculation
Order date: April 10, 2023
Estimated delivery date (5 business days later): April 17, 2023
Practical example 4: Date grouping
Events grouped by day:
Wednesday, April 5, 2023:
  - Meeting 1 at 10:00 AM
  - Lunch at 12:30 PM
Thursday, April 6, 2023:
  - Meeting 2 at 2:00 PM
Friday, April 7, 2023:
  - Conference at 9:00 AM
  - Workshop at 1:00 PM
[M]:

8. Creating a Date Picker

Let's create a simple date picker using date-fns to generate the calendar data.

[10]:
// Function to generate calendar data for a month
function generateCalendarMonth(year, month) {
const firstDayOfMonth = new Date(year, month, 1);
const lastDayOfMonth = dateFns.lastDayOfMonth(firstDayOfMonth);
const daysInMonth = dateFns.getDaysInMonth(firstDayOfMonth);
// Get the day of week for the first day (0 = Sunday, 6 = Saturday)
const firstDayOfWeek = dateFns.getDay(firstDayOfMonth);
// Create an array to hold all calendar days
const calendarDays = [];
// Add empty slots for days before the first day of the month
for (let i = 0; i < firstDayOfWeek; i++) {
calendarDays.push(null);
}
// Add all days of the month
for (let day = 1; day <= daysInMonth; day++) {
calendarDays.push(new Date(year, month, day));
}
return {
year,
month,
monthName: dateFns.format(firstDayOfMonth, 'MMMM'),
days: calendarDays
};
}

// Generate calendar for the current month
const currentYear = dateFns.getYear(today);
const currentMonth = dateFns.getMonth(today);
const calendar = generateCalendarMonth(currentYear, currentMonth);

// Display the calendar
Calendar for March 2025:
Sun	Mon	Tue	Wed	Thu	Fri	Sat 
   	   	   	   	   	   	  1  
  2 	  3 	  4 	  5 	  6 	  7 	  8  
  9 	 10 	 11 	 12 	 13 	 14 	 15  
 16 	 17 	 18 	[19]	 20 	 21 	 22  
 23 	 24 	 25 	 26 	 27 	 28 	 29  
 30 	 31  
[M]:

9. Working with Recurring Events

Let's demonstrate how to work with recurring events using date-fns.

[11]:
// Function to generate dates for a recurring event
function generateRecurringDates(startDate, endDate, frequency, count) {
const dates = [];
let currentDate = startDate;
while (dates.length < count && dateFns.isBefore(currentDate, endDate)) {
dates.push(currentDate);
// Apply the frequency
switch (frequency) {
case 'daily':
currentDate = dateFns.addDays(currentDate, 1);
break;
case 'weekly':
currentDate = dateFns.addWeeks(currentDate, 1);
break;
case 'biweekly':
currentDate = dateFns.addWeeks(currentDate, 2);
break;
case 'monthly':
currentDate = dateFns.addMonths(currentDate, 1);
break;
case 'yearly':
currentDate = dateFns.addYears(currentDate, 1);
break;
default:
throw new Error(`Unknown frequency: ${frequency}`);
}
}
return dates;
}

// Example: Generate dates for a weekly meeting for the next 2 months
const meetingStart = new Date(2023, 3, 3, 10, 0); // April 3, 2023, 10:00 AM
const meetingEnd = dateFns.addMonths(meetingStart, 2); // 2 months from start
Weekly meeting schedule:
Meeting 1: Monday, April 3, 2023 10:00 AM
Meeting 2: Monday, April 10, 2023 10:00 AM
Meeting 3: Monday, April 17, 2023 10:00 AM
Meeting 4: Monday, April 24, 2023 10:00 AM
Meeting 5: Monday, May 1, 2023 10:00 AM
Meeting 6: Monday, May 8, 2023 10:00 AM
Meeting 7: Monday, May 15, 2023 10:00 AM
Meeting 8: Monday, May 22, 2023 10:00 AM
Meeting 9: Monday, May 29, 2023 10:00 AM

Monthly team lunch schedule:
Lunch 1: Saturday, April 15, 2023 12:30 PM
Lunch 2: Monday, May 15, 2023 12:30 PM
Lunch 3: Thursday, June 15, 2023 12:30 PM
Lunch 4: Saturday, July 15, 2023 12:30 PM
Lunch 5: Tuesday, August 15, 2023 12:30 PM
Lunch 6: Friday, September 15, 2023 12:30 PM
Lunch 7: Sunday, October 15, 2023 12:30 PM
Lunch 8: Wednesday, November 15, 2023 12:30 PM
Lunch 9: Friday, December 15, 2023 12:30 PM
Lunch 10: Monday, January 15, 2024 12:30 PM
Lunch 11: Thursday, February 15, 2024 12:30 PM
Lunch 12: Friday, March 15, 2024 12:30 PM
[M]:

10. Date Localization

The date-fns library supports localization for different languages and regions.

[12]:
// Import some locales
import { es, fr, de, ja, ru } from 'https://cdn.skypack.dev/date-fns/locale';

// Date localization examples
console.log("Date localization examples:\n");

const sampleDate = new Date(2023, 3, 15); // April 15, 2023

// Format date in different languages
console.log("English (default):", dateFns.format(sampleDate, 'PPPP'), "\n");

console.log("Spanish:", dateFns.format(sampleDate, 'PPPP', { locale: es }), "\n");

console.log("French:", dateFns.format(sampleDate, 'PPPP', { locale: fr }), "\n");

console.log("German:", dateFns.format(sampleDate, 'PPPP', { locale: de }), "\n");

console.log("Japanese:", dateFns.format(sampleDate, 'PPPP', { locale: ja }), "\n");

console.log("Russian:", dateFns.format(sampleDate, 'PPPP', { locale: ru }), "\n");

// Format relative time in different languages
const yesterday = dateFns.subDays(new Date(), 1);

console.log("\nRelative time examples:\n");
console.log("English (default):", dateFns.formatRelative(yesterday, new Date()), "\n");

console.log("Spanish:", dateFns.formatRelative(yesterday, new Date(), { locale: es }), "\n");

console.log("French:", dateFns.formatRelative(yesterday, new Date(), { locale: fr }), "\n");

console.log("German:", dateFns.formatRelative(yesterday, new Date(), { locale: de }), "\n");

console.log("Japanese:", dateFns.formatRelative(yesterday, new Date(), { locale: ja }), "\n");

console.log("Russian:", dateFns.formatRelative(yesterday, new Date(), { locale: ru }), "\n");
Error during execution: Cannot find module 'https://cdn.skypack.dev/date-fns/locale' Require stack: - /home/bfwsdlnpboac0izci3s7i3zj938f6s-jbm1/watcher.js
[M]:

11. Working with Date Durations

Let's explore how to work with durations between dates.

[13]:
// Duration examples
console.log("Duration examples:\n");

const startDateTime = new Date(2023, 0, 1, 8, 30); // January 1, 2023, 8:30 AM
const endDateTime = new Date(2023, 0, 5, 16, 45); // January 5, 2023, 4:45 PM

// Calculate duration in various units
const durationInMs = dateFns.intervalToDuration({
start: startDateTime,
end: endDateTime
});

console.log("Duration between dates:", JSON.stringify(durationInMs), "\n");

// Format the duration in a human-readable way
function formatDuration(duration) {
const parts = [];
if (duration.years) parts.push(`${duration.years} year${duration.years !== 1 ? 's' : ''}`);
if (duration.months) parts.push(`${duration.months} month${duration.months !== 1 ? 's' : ''}`);
if (duration.days) parts.push(`${duration.days} day${duration.days !== 1 ? 's' : ''}`);
if (duration.hours) parts.push(`${duration.hours} hour${duration.hours !== 1 ? 's' : ''}`);
if (duration.minutes) parts.push(`${duration.minutes} minute${duration.minutes !== 1 ? 's' : ''}`);
if (duration.seconds) parts.push(`${duration.seconds} second${duration.seconds !== 1 ? 's' : ''}`);
return parts.join(', ');
}

console.log("Formatted duration:", formatDuration(durationInMs), "\n");

// Calculate specific duration units
console.log("Duration in days:", dateFns.differenceInDays(endDateTime, startDateTime), "\n");
console.log("Duration in hours:", dateFns.differenceInHours(endDateTime, startDateTime), "\n");
console.log("Duration in minutes:", dateFns.differenceInMinutes(endDateTime, startDateTime), "\n");
console.log("Duration in seconds:", dateFns.differenceInSeconds(endDateTime, startDateTime), "\n");
console.log("Duration in milliseconds:", dateFns.differenceInMilliseconds(endDateTime, startDateTime), "\n");
Duration examples:
Duration between dates: {"days":4,"hours":8,"minutes":15} 
Formatted duration: 4 days, 8 hours, 15 minutes 
Duration in days: 4 
Duration in hours: 104 
Duration in minutes: 6255 
Duration in seconds: 375300 
Duration in milliseconds: 375300000 
Business days between dates: 3 
[M]:

12. Date Validation and Manipulation

Let's explore date validation and manipulation functions.

[14]:
// Date validation examples
console.log("Date validation examples:\n");

// Check if a date is valid
const validDate = new Date(2023, 3, 15);
const invalidDate = new Date('Invalid Date');

console.log("Is validDate valid?", dateFns.isValid(validDate), "\n");
console.log("Is invalidDate valid?", dateFns.isValid(invalidDate), "\n");

// Check if a date exists
function isDateValid(year, month, day) {
const date = new Date(year, month - 1, day); // month is 0-indexed in JavaScript
return dateFns.isValid(date) && date.getMonth() === month - 1 && date.getDate() === day;
}

console.log("Is February 29, 2023 valid?", isDateValid(2023, 2, 29), "\n"); // Not a leap year
console.log("Is February 29, 2024 valid?", isDateValid(2024, 2, 29), "\n"); // Leap year
console.log("Is April 31, 2023 valid?", isDateValid(2023, 4, 31), "\n"); // April has 30 days

// Date manipulation examples
console.log("\nDate manipulation examples:\n");

// Set specific parts of a date
let date = new Date(2023, 3, 15, 10, 30); // April 15, 2023, 10:30 AM

// Set year
date = dateFns.setYear(date, 2024);
console.log("After setting year to 2024:", dateFns.format(date, 'MMMM d, yyyy HH:mm'), "\n");

// Set month
date = dateFns.setMonth(date, 5); // June (0-indexed)
console.log("After setting month to June:", dateFns.format(date, 'MMMM d, yyyy HH:mm'), "\n");

// Set day of month
date = dateFns.setDate(date, 20);
Date validation examples:
Is validDate valid? true 
Is invalidDate valid? false 
Is February 29, 2023 valid? false 
Is February 29, 2024 valid? true 
Is April 31, 2023 valid? false 

Date manipulation examples:
After setting year to 2024: April 15, 2024 10:30 
After setting month to June: June 15, 2024 10:30 
After setting day to 20: June 20, 2024 10:30 
After setting hours to 14 (2 PM): June 20, 2024 14:30 
After setting minutes to 45: June 20, 2024 14:45 
After resetting to start of day: June 20, 2024 00:00:00 
After setting to end of day: June 20, 2024 23:59:59 
[M]:

13. Building a Date Utility Library

Let's create a small utility library with common date operations using date-fns.

[15]:
// Define a DateUtils class with common date operations
class DateUtils {
// Format a date with a default format
static formatDate(date, format = 'yyyy-MM-dd') {
return dateFns.format(date, format);
}
// Format a date with time
static formatDateTime(date, format = 'yyyy-MM-dd HH:mm:ss') {
return dateFns.format(date, format);
}
// Parse a date string
static parseDate(dateStr, format = 'yyyy-MM-dd') {
return dateFns.parse(dateStr, format, new Date());
}
// Check if a date is valid
static isValidDate(date) {
return dateFns.isValid(date);
}
// Get the difference between two dates in days
static getDaysDifference(startDate, endDate) {
return dateFns.differenceInDays(endDate, startDate);
}
// Add days to a date
static addDays(date, days) {
return dateFns.addDays(date, days);
}
// Get the start of a month
static getStartOfMonth(date) {
return dateFns.startOfMonth(date);
}
DateUtils examples:
Formatted date: 2023-04-15 
Formatted date-time: 2023-04-15 00:00:00 
Is valid date? true 
Days difference from today: 704 
Date after adding 10 days: 2023-04-25 
Start of month: 2023-04-01 
End of month: 2023-04-30 
Is today? false 
Is in the past? true 
Is in the future? false 
Relative time: almost 2 years ago 
Day of week: Saturday 
Is weekend? true 
[M]:

Summary

This notebook has demonstrated the power and flexibility of the date-fns library for handling dates in JavaScript. We've covered:

  1. Basic Date Formatting: Using the format function to display dates in various formats
  2. Date Arithmetic: Adding and subtracting time units from dates
  3. Date Comparisons: Comparing dates and checking conditions
  4. Working with Date Ranges: Handling intervals and ranges of dates
  5. Parsing Dates: Converting strings to date objects
  6. Timezone Handling: Working with dates in different timezones
  7. Practical Examples: Real-world use cases for date manipulation
  8. Creating a Date Picker: Generating calendar data
  9. Working with Recurring Events: Generating dates for recurring events
  10. Date Localization: Formatting dates in different languages
  11. Working with Date Durations: Calculating and formatting time durations
  12. Date Validation and Manipulation: Validating and modifying date components
  13. Building a Date Utility Library: Creating reusable date utilities

The date-fns library provides a comprehensive set of functions for working with dates in JavaScript, making it a powerful alternative to other date libraries like Moment.js. Its modular design allows for tree-shaking, which can significantly reduce bundle sizes in production applications.

Key advantages of using date-fns include:

  • Immutability: All functions return new Date objects instead of modifying existing ones
  • Modularity: Import only the functions you need
  • Type Safety: Written in TypeScript with excellent type definitions
  • Consistency: Consistent API design across all functions
  • Performance: Lightweight and efficient implementation
  • I18n Support: Excellent internationalization capabilities

For more information, visit the date-fns documentation.

Sign in to save your work and access it from anywhere