blog post

Working with Dates in JavaScript

This post will guide you through the essentials of handling dates in JavaScript, using the built-in Date object. We'll explore creating dates, formatting them, performing date calculations, comparing dates and handling time zone conversions.

How To Create Date In JavaScript

You can create a date in JavaScript using the Date constructor. You can create a date object using different formats:

js
// Current date and time const now = new Date(); console.log(now); // Specific date and time (YYYY, MM, DD, HH, MM, SS, MS) const specificDate = new Date(2024, 6, 15, 10, 30, 0, 0); console.log(specificDate); // From timestamp (epoch timestamp, milliseconds since January 1, 1970) const timestampDate = new Date(1718477533698); console.log(timestampDate); // From date string (ISO format) const stringDate = new Date("2024-06-15T10:30:00Z"); console.log(stringDate);

How To Get Parts of Date

JavaScript provides methods to get individual components of a date, such as seconds, minutes, hours, days, etc.

These methods allow you to extract specific parts of a date object:

js
const date = new Date("2024-06-15T10:20:30Z"); // Getting Year const year = date.getFullYear(); console.log(year); // 2024 // Getting Month (0-11, where 0 is January and 11 is December) const month = date.getMonth(); console.log(month); // 5 (June) // Getting Date of the Month (1-31) const dayOfMonth = date.getDate(); console.log(dayOfMonth); // 15 // Getting Day of the Week (0-6, where 0 is Sunday and 6 is Saturday) const dayOfWeek = date.getDay(); console.log(dayOfWeek); // 6 (Saturday) // Getting Hours (0-23) const hours = date.getHours(); console.log(hours); // 10 // Getting Minutes (0-59) const minutes = date.getMinutes(); console.log(minutes); // 20 // Getting Seconds (0-59) const seconds = date.getSeconds(); console.log(seconds); // 30 // Getting Milliseconds (0-999) const milliseconds = date.getMilliseconds(); console.log(milliseconds); // 0 // Getting UTC Hours const utcHours = date.getUTCHours(); console.log(utcHours); // 10

How To Format Dates

JavaScript provides methods to format dates in a human-readable way.

Here are some commonly used methods:

  • toDateString - converts the date portion of a Date object to a string
  • toTimeString - converts the time portion of a Date object to a string
  • toLocaleDateString - converts the date to a string using locale conventions
  • toLocaleTimeString - converts the time to a string using locale conventions
  • toISOString - converts the date to an ISO 8601 string

Now let's explore these methods in action:

js
const date = new Date(); // e.g., "Sat Jun 15 2024" console.log(date.toDateString()); // e.g., "10:33:30 GMT+0300 (Eastern European Summer Time)" console.log(date.toTimeString()); // e.g., "6/15/2024" console.log(date.toLocaleDateString("en-US")); // e.g., "10:33:30 AM" console.log(date.toLocaleTimeString("en-US")); // e.g., "2024-06-15T07:33:30.000Z" console.log(date.toISOString());

Calculations between Date Objects

JavaScript allows you to add or subtract time units from dates.

You can add seconds, minutes, hours, days, months, years. For example:

js
const today = new Date(); // Adding minutes const newDate = new Date(today); newDate.setMinutes(newDate.getMinutes() + 10); console.log(newDate); // Adding days const tomorrow = new Date(today); tomorrow.setDate(tomorrow.getDate() + 1); console.log(tomorrow); // Adding months const nextMonth = new Date(today); nextMonth.setMonth(nextMonth.getMonth() + 1); console.log(nextMonth);

Here is how you can subtract date units:

js
const today = new Date(); // Subtracting minutes const newDate = new Date(today); newDate.setMinutes(newDate.getMinutes() - 10); console.log(newDate); // Subtracting days const yesterday = new Date(today); yesterday.setDate(today.getDate() - 1); console.log(yesterday); // Subtracting years const lastYear = new Date(today); lastYear.setFullYear(today.getFullYear() - 1); console.log(lastYear);

To add or subtract dates, you need to deal with the time values in milliseconds, since JavaScript Date objects don't directly support arithmetic operations.

To add a specific time interval to a date, convert the interval to milliseconds and add it to the date's time value:

js
const date = new Date("2024-06-15T10:00:00Z"); const daysToAdd = 5; // Adding days const resultDate = new Date(date.getTime() + (daysToAdd * 24 * 60 * 60 * 1000)); console.log(resultDate);

To subtract a time interval from a date, convert the interval to milliseconds and subtract it from the date's time value:

js
const date = new Date("2024-06-15T10:00:00Z"); const daysToSubtract = 3; // Subtracting days const resultDate = new Date(date.getTime() - (daysToSubtract * 24 * 60 * 60 * 1000)); console.log(resultDate);

How To Compare Dates in JavaScript

JavaScript allows you to compare dates using comparison operators. Since dates are essentially numbers (milliseconds since January 1, 1970), you can directly compare them:

js
const date1 = new Date("2024-06-15T10:00:00Z"); const date2 = new Date("2024-06-16T10:00:00Z"); console.log(date1 > date2); // false console.log(date1 < date2); // true // false (compares exact time) console.log(date1.getTime() === date2.getTime());

To find the difference between two dates, subtract one date from the other. This gives you the difference in milliseconds, which can then be converted to other units:

js
const date1 = new Date("2024-06-15T10:00:00Z"); const date2 = new Date("2024-06-20T10:00:00Z"); const diffInMilliseconds = date2 - date1; const diffInDays = diffInMilliseconds / (24 * 60 * 60 * 1000); console.log(diffInDays); // 5

How To Use Date Static Methods

Date class provides several useful static methods for handling dates and times. Let's explore them:

Date.now() - returns the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC (the Unix Epoch). This method is useful for measuring time intervals and for generating timestamps.

js
const milliseconds = Date.now(); console.log(milliseconds); // e.g., 1718477533698

Date.parse() - parses a date string and returns the number of milliseconds, equivalent to the date and time described by the string. This method is helpful for converting date strings into a format that can be used to create Date objects or perform date calculations.

js
const timestamp = Date.parse("2024-06-15T10:00:00Z"); console.log(timestamp);

Date.UTC() - accepts date components (year, month, day, hours, minutes, seconds, milliseconds) and returns the number of milliseconds in UTC for the given date and time. This method is useful for creating Date objects in UTC, especially when dealing with time zone differences.

js
// Note: months are 0-based (0 = January, 11 = December) const timestamp = Date.UTC(2024, 5, 15, 10, 0, 0); console.log(timestamp);

How To Handle Time Zones Conversions

JavaScript's Date object operates in the local time zone of the user's system. To handle different time zones, you can use UTC methods:

js
const date = new Date(); // Getting UTC date and time console.log(date.getUTCDate()); console.log(date.getUTCHours()); // Setting UTC date and time const utcDate = new Date(); utcDate.setUTCFullYear(2024); utcDate.setUTCMonth(6); utcDate.setUTCDate(15); console.log(utcDate.toISOString());

Dealing with UTC time is particularly useful when fetching data from the server. Often server stores dates in UTC and frontend is responsible to transform it to the user's local time.

Let's explore such an example with a real API that returns datetime info:

js
async function fetchUtcTimeAsync() { try { const response = await fetch("https://worldtimeapi.org/api/timezone/Europe/London"); const data = await response.json(); return data.utc_datetime; } catch (error) { console.error("Error fetching UTC time for London:", error); } } const utcDateTimeString = await fetchUtcTimeAsync(); const utcDate = new Date(utcDateTimeString);

After fetching the utc datetime string, we can use it to create a Date object.

To convert it to the local time, we can use the getTime function and create a new Date object:

js
const localDate = new Date(utcDate.getTime()); console.log("UTC Date and Time:", utcDate.toISOString()); console.log("Local Date and Time:", localDate.toString());

Summary

Today we explored how to:

  • create dates
  • extract part of dates
  • format dates
  • perform date calculations and comparison
  • how to use Date static methods
  • and how to handle time zones

Now you're fully equipped with information on how to work with Dates in JavaScript, so you can efficiently manage dates and times in your applications.

Hope you find this blog post useful. Happy coding!

Improve Your .NET and Architecture Skills

Join my community of 1800+ developers and architects.

Each week you will get 2 practical tips with best practises and architecture advice.