Skip to content
DevNursery.com - New Web Developer Docs
GitHub

Javascript Dates

JavaScript Dates

Working with dates and times is a common task in web development, and JavaScript provides a built-in Date object to handle various date-related operations. In this section, we’ll explore JavaScript dates, how to create and manipulate them, and common use cases.

Creating Dates

You can create a new Date object in JavaScript using the following methods:

// Current date and time
const currentDate = new Date();

// Specific date and time (year, month [0-11], day, hour, minute, second)
const customDate = new Date(2023, 8, 15, 14, 30, 0); // September 15, 2023, 14:30:00

// Parsing a date string (formatted as yyyy-mm-dd)
const parsedDate = new Date('2023-09-15');

Accessing Date Components

Once you have a Date object, you can access various date components like the year, month, day, and so on:

const date = new Date();

const year = date.getFullYear();
const month = date.getMonth(); // Month is 0-indexed (0 = January, 11 = December)
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const milliseconds = date.getMilliseconds();

console.log(`Year: ${year}, Month: ${month}, Day: ${day}`);

Formatting Dates

To display dates in a human-readable format, you can construct custom date strings using the Date object’s methods or utilize libraries like Intl.DateTimeFormat:

const date = new Date();

// Formatting with Date methods
const formattedDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;

// Formatting with Intl.DateTimeFormat
const options = { year: 'numeric', month: 'long', day: 'numeric' };
const formattedDateIntl = new Intl.DateTimeFormat('en-US', options).format(date);

console.log(`Formatted Date (Custom): ${formattedDate}`);
console.log(`Formatted Date (Intl): ${formattedDateIntl}`); 

Manipulating Dates

You can perform various operations on Date objects, such as adding or subtracting days, months, or years:

const date = new Date();

// Adding days
date.setDate(date.getDate() + 7);

// Adding months
date.setMonth(date.getMonth() + 1);

// Adding years
date.setFullYear(date.getFullYear() + 1);

console.log(`Updated Date: ${date}`);

Comparing Dates

To compare two dates, you can use comparison operators (<, >, <=, >=) or the getTime() method, which returns the number of milliseconds since January 1, 1970 (UTC):

const date1 = new Date('2023-09-15');
const date2 = new Date('2023-09-20');

if (date1.getTime() < date2.getTime()) {
  console.log('date1 is earlier than date2');
} else {
  console.log('date1 is later than date2');
}

Working with Time Zones

JavaScript’s Date object operates in the user’s local time zone. If you need to work with different time zones, you can use libraries like moment-timezone or the Intl.DateTimeFormat API with options to specify the desired time zone.

const date = new Date();

const options = {
  timeZone: 'America/New_York',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  timeZoneName: 'short',
};

const formattedTime = new Intl.DateTimeFormat('en-US', options).format(date);
console.log(`New York Time: ${formattedTime}`);

JavaScript dates provide a powerful way to work with date and time information in web applications. Whether you’re displaying dates, performing date calculations, or handling time zones, the Date object and related APIs offer the necessary tools to manage date-related tasks effectively.

Date Operations Chart

Type of Date OperationSyntaxExample
Creating a New Datenew Date()const currentDate = new Date();
new Date(year, month, day)const customDate = new Date(2023, 8, 15);
Parsing a Date Stringnew Date(dateString)const parsedDate = new Date('2023-09-15');
Accessing Yeardate.getFullYear()const year = date.getFullYear();
Accessing Monthdate.getMonth()const month = date.getMonth();
Accessing Daydate.getDate()const day = date.getDate();
Accessing Hoursdate.getHours()const hours = date.getHours();
Accessing Minutesdate.getMinutes()const minutes = date.getMinutes();
Accessing Secondsdate.getSeconds()const seconds = date.getSeconds();
Accessing Millisecondsdate.getMilliseconds()const milliseconds = date.getMilliseconds();
Formatting DateCustom Formattingconst formattedDate = `${year}-${month + 1}-${day}`;
Formatting DateIntl.DateTimeFormatconst formattedDateIntl = new Intl.DateTimeFormat('en-US', options).format(date);
Adding Daysdate.setDate(date.getDate() + daysToAdd)date.setDate(date.getDate() + 7);
Adding Monthsdate.setMonth(date.getMonth() + monthsToAdd)date.setMonth(date.getMonth() + 1);
Adding Yearsdate.setFullYear(date.getFullYear() + yearsToAdd)date.setFullYear(date.getFullYear() + 1);
Comparing DatesUsing Comparison Operators (<, >, <=, >=)if (date1.getTime() < date2.getTime()) { /* Comparison logic */ }
Comparing DatesUsing getTime() Methodif (date1.getTime() < date2.getTime()) { /* Comparison logic */ }
Working with Time ZonesIntl.DateTimeFormat with timeZone optionconst formattedTime = new Intl.DateTimeFormat('en-US', options).format(date);
Accessing Day of Weekdate.getDay()const dayOfWeek = date.getDay();
Accessing Day of Week (Name)Intl.DateTimeFormat with weekday optionconst dayName = new Intl.DateTimeFormat('en-US', { weekday: 'long' }).format(date);
Accessing Month (Name)Intl.DateTimeFormat with month optionconst monthName = new Intl.DateTimeFormat('en-US', { month: 'long' }).format(date);
Formatting TimeCustom Formattingconst formattedTime = `${hours}:${minutes}:${seconds}`;
Formatting TimeIntl.DateTimeFormat with hour, minute, and second optionsconst formattedTimeIntl = new Intl.DateTimeFormat('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric' }).format(date);
UTC Datedate.toISOString()const utcDate = date.toISOString();
UNIX Timestampdate.getTime()const timestamp = date.getTime();
Date Difference (in Days)Calculate the difference in days between two datesconst daysDifference = Math.floor((date2 - date1) / (1000 * 60 * 60 * 24));
Date Difference (in Hours)Calculate the difference in hours between two datesconst hoursDifference = Math.floor((date2 - date1) / (1000 * 60 * 60));
Date Difference (in Minutes)Calculate the difference in minutes between two datesconst minutesDifference = Math.floor((date2 - date1) / (1000 * 60));
Date Difference (in Seconds)Calculate the difference in seconds between two datesconst secondsDifference = Math.floor((date2 - date1) / 1000);
Set Timedate.setHours(hours)date.setHours(14);
Set Timedate.setMinutes(minutes)date.setMinutes(30);
Set Timedate.setSeconds(seconds)date.setSeconds(45);
Set Timedate.setMilliseconds(milliseconds)date.setMilliseconds(500);
Beginning/End of MonthFinding the first day of the monthdate.setDate(1);
Beginning/End of MonthFinding the last day of the monthdate.setMonth(date.getMonth() + 1, 0);
Adding/Subtracting Weeksdate.setDate(date.getDate() + (7 * weeksToAdd))date.setDate(date.getDate() + (7 * 2));
Unix Timestamp to DateCreating a Date from a Unix timestampconst unixTimestamp = 1631767200000; const unixDate = new Date(unixTimestamp);
Daylight Saving TimeChecking if the date is during DSTconst isDST = date.getTimezoneOffset() < -300;

DateFNS

Date-FNS (Date Functions) is a popular JavaScript library for manipulating and formatting dates and times in a simple and consistent manner. It offers a wide range of functions for working with dates, including parsing, formatting, and calculating differences between dates. Date-FNS is designed to be easy to use and is often chosen for its simplicity and reliability.

Here’s an overview of Date-FNS:

What is Date-FNS?

Date-FNS is a JavaScript library that provides a collection of utility functions for working with dates and times. It is not a full-fledged date and time library like Moment.js but focuses on providing specific date and time operations in a modular and efficient way. Date-FNS follows the philosophy of being “like lodash for dates.”

How to Use Date-FNS

Using Date-FNS via CDN:

You can include Date-FNS directly in your HTML file using a Content Delivery Network (CDN). Add the following script tag to your HTML file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/2.23.0/date-fns.min.js"></script>

Now, you can use Date-FNS functions in your JavaScript code.

Using Date-FNS via npm:

To use Date-FNS in a Node.js project or with a build system like Webpack or Parcel, you can install it via npm (Node Package Manager). Open your terminal and run:

npm install date-fns

Then, you can import Date-FNS functions in your JavaScript code like this:

const { format, parseISO, differenceInDays } = require('date-fns');

Overview of Usage

Date-FNS provides a variety of functions that cover common date and time operations. Here’s a brief overview of some of the most commonly used functions:

Formatting Dates:

You can format dates using functions like format. For example:

const formattedDate = format(new Date(), 'yyyy-MM-dd');

Parsing Dates:

Parse date strings into JavaScript Date objects using functions like parseISO:

const date = parseISO('2023-09-30T12:00:00');

Calculating Date Differences:

Find the difference between two dates with functions like differenceInDays:

const startDate = new Date('2023-09-01');
const endDate = new Date('2023-09-30');
const daysDifference = differenceInDays(endDate, startDate);

Adding and Subtracting Time:

Functions like addDays and subMonths allow you to manipulate dates:

const newDate = addDays(new Date(), 7);

Comparing Dates:

Functions like isAfter, isBefore, and isEqual help you compare dates:

const isFuture = isAfter(new Date('2024-01-01'), new Date());

Date-FNS provides many more functions, each with its specific purpose. You can consult the official documentation for a comprehensive list of functions and their usage: Date-FNS Documentation.

DateFNS Chart

OperationSyntaxExample
Format a Dateformat(date, formatString)format(new Date(), 'yyyy-MM-dd HH:mm:ss')
Parse a DateparseISO(dateString)parseISO('2023-09-30T12:00:00')
Calculate Date DiffdifferenceInDays(dateA, dateB)differenceInDays(new Date('2023-09-30'), new Date('2023-09-01'))
Add DaysaddDays(date, amount)addDays(new Date(), 7)
Subtract MonthssubMonths(date, amount)subMonths(new Date(), 2)
Is Date AfterisAfter(dateA, dateB)isAfter(new Date('2024-01-01'), new Date())
Is Date BeforeisBefore(dateA, dateB)isBefore(new Date('2023-09-01'), new Date())
Is Date EqualisEqual(dateA, dateB)isEqual(new Date('2023-09-30'), new Date())
Get Day of the WeekgetDay(date)getDay(new Date('2023-09-30'))
Get MonthgetMonth(date)getMonth(new Date('2023-09-30'))
Get YeargetYear(date)getYear(new Date('2023-09-30'))
Get HoursgetHours(date)getHours(new Date('2023-09-30T12:00:00'))
Get MinutesgetMinutes(date)getMinutes(new Date('2023-09-30T12:30:00'))
Get SecondsgetSeconds(date)getSeconds(new Date('2023-09-30T12:45:15'))
Add HoursaddHours(date, amount)addHours(new Date(), 3)
Add MinutesaddMinutes(date, amount)addMinutes(new Date(), 30)
Add SecondsaddSeconds(date, amount)addSeconds(new Date(), 15)
Start of DaystartOfDay(date)startOfDay(new Date('2023-09-30T16:45:00'))
End of DayendOfDay(date)endOfDay(new Date('2023-09-30T16:45:00'))
Get Days in MonthgetDaysInMonth(date)getDaysInMonth(new Date('2023-09-01'))
Format Relative TimeformatDistanceToNow(date)formatDistanceToNow(new Date('2023-09-30T12:00:00'))
Is Leap YearisLeapYear(date)isLeapYear(new Date('2024-01-01'))
Set YearsetYear(date, year)setYear(new Date(), 2023)
Set MonthsetMonth(date, month)setMonth(new Date(), 5)
Subtract DayssubDays(date, amount)subDays(new Date(), 7)
Add MonthsaddMonths(date, amount)addMonths(new Date(), 3)
Set DaysetDay(date, dayOfWeek, options)setDay(new Date(), 1, { weekStartsOn: 1 })
Set HourssetHours(date, hours)setHours(new Date(), 10)
Set MinutessetMinutes(date, minutes)setMinutes(new Date(), 30)
Set SecondssetSeconds(date, seconds)setSeconds(new Date(), 45)
Get TimegetTime(date)getTime(new Date())
Get ISO WeekgetISOWeek(date)getISOWeek(new Date('2023-09-30'))
Get ISO YeargetISOYear(date)getISOYear(new Date('2023-09-30'))
Get Day of the MonthgetDate(date)getDate(new Date('2023-09-30'))
Get Timezone OffsetgetTimezoneOffset(date)getTimezoneOffset(new Date())
Add YearsaddYears(date, amount)addYears(new Date(), 5)
Start of MonthstartOfMonth(date)startOfMonth(new Date('2023-09-15'))
End of MonthendOfMonth(date)endOfMonth(new Date('2023-09-15'))
Set Minutes and SecondssetMinutesAndSeconds(date, minutes, seconds)setMinutesAndSeconds(new Date(), 15, 30)
Set Hours and MinutessetHoursAndMinutes(date, hours, minutes)setHoursAndMinutes(new Date(), 9, 45)
Get Unix TimestampgetUnixTime(date)getUnixTime(new Date())
Set Unix TimestampfromUnixTime(unixTimestamp)fromUnixTime(1633000000)
Get QuartergetQuarter(date)getQuarter(new Date('2023-09-30'))
Is TodayisToday(date)isToday(new Date())