Mastering Dates in JavaScript: The Ultimate Guide to Date & Time Handling

forthegeeks

Manjunath Shenoy

Posted on November 11, 2024

Mastering Dates in JavaScript: The Ultimate Guide to Date & Time Handling

1. Introduction

In this tutorial, we’ll dive into everything you need to know about dates in JavaScript, starting with the basics. I’ll be doing the entire walkthrough on Microsoft Edge, though you can easily follow along on Chrome as well. We’ll also cover some handy tricks to simulate different time zones right from your browser — yes, you can test across time zones directly in your browser! Plus, we’ll address common challenges and questions that newcomers often face along the way.
Rest assured, if you read through this article carefully, you’ll gain a solid understanding of dates. I’ve worked to combine all the essential information here for your benefit. Pay close attention, and consider printing the included image to keep as a handy reference for day-to-day use — I believe it will be a valuable resource!

2. Understanding Time Standards and Time Zones

2.1 UTC (Coordinated Universal Time)

✅UTC is a standard, universal time zone that serves as a baseline for all other time zones.

✅ UTC and GMT: Although UTC and GMT show the same time, they’re not exactly the same. GMT is a time zone, while UTC is a time standard.
The differences are minor and don’t typically affect date handling in JavaScript, so we can treat them as equivalent for most coding purposes.

2.2 Relative Time Zones

✅ Every other time zone is essentially an offset from UTC. For example, I’m in Australia in the AEDT time zone, which is GMT+11 (or UTC+11). JavaScript works with these offsets to calculate times accurately across zones. Below is a normal Date() object created(uses browser’s time zone) and then same in UTCString format

3. Date Formats in JavaScript

3.1 ISO 8601 format

✅ Returns a string Date and Time in ISO 8601 format. The UTC we saw above is a standard that provides a universal time reference, while ISO 8601, on the other hand, is a standardized way to format date and time values to ensure consistency ,clarity in communication and avoid confusion

✅ To understand why ISO format is required, lets think of a small story

Three old school friends — Mike in New York, Laurie in London, and Taro in Tokyo — decided it was finally time to plan a reunion. They hadn’t seen each other in years and wanted to lock down a date to catch up in person. After a long call, they agreed Mike would send an email with the details.
Later that night, Mike sent a quick email saying, “Let’s meet on 01/12/2025 at 00:00.”Laurie, in London, saw the email and thought, “Perfect, December 1st! I’ve got almost a full year to plan.” Taro, in Tokyo, also read 01/12/2025 as December 1st, so he marked it in his calendar and went back to his busy schedule.
But Mike had actually meant January 12, and New York typically formats dates as MM/DD/YYYY. On January 10, he messaged both of them: “Can’t wait to see you guys in a couple of days!”
Both Laurie and Taro were shocked. “Wait — January? I thought we were meeting in December!” Laurie panicked as he realized he’d completely misinterpreted the date, and Taro, realizing his own mistake, scrambled to find a last-minute flight.
After the date confusion, the friends agreed to use ISO 8601 format for all future plans, sticking to 2025–01–12T00:00:00Z for clear communication. Thanks to this new rule, their reunion was finally set — no misunderstandings, no panic, just a simple date everyone understood, no matter where they are.

ISODateFormat

3.2 Locale-Based Format

✅ Returns Date object as a string, using locale settings. We can use this to format date in a particular way using locale options.

✅ Egamples below, see how date output varies based on locales

// Currently in 'London' Location i.e "en-GB" locale
new Date(); // Sun Nov 10 2024 23:34:22 GMT+0000 (Greenwich Mean Time)
new Date().toLocaleDateString();// '10/11/2024'
new Date().toLocaleDateString("en-US"); // '11/10/2024'
Enter fullscreen mode Exit fullscreen mode

4. Formatting Dates in JavaScript
4.1 Formatting Dates with Intl.DateTimeFormat vs toLocaleDateString

JavaScript provides two primary methods for locale-based date formatting:

✅ Intl.DateTimeFormat is a standalone object allowing flexible formatting options for dates and times.

const options = { 
day: "numeric",
month: "long",
year: "numeric" 
};

new Date().toLocaleDateString("en-GB", options); // "10 November 2024"
Enter fullscreen mode Exit fullscreen mode

✅toLocaleDateString is a Date method that returns the date as a localized string. Same output as above

const options = { 
day: "numeric",
month: "long",
year: "numeric" 
};

new Date().toLocaleDateString("en-GB", options); // "10 November 2024"
Enter fullscreen mode Exit fullscreen mode

4.2 Different Date Formats in Practice

✅We have toUTCString() for UTC dates , toISOString() for ISO format, and toLocaleDateString() for date-only format

new Date().toUTCString(); // e.g., 'Sun, 10 Nov 2024 23:51:54 GMT'
new Date().toLocaleString(); // e.g., '10/11/2024, 11:52:13 pm'
new Date().toISOString(); // e.g., '2024-11-10T23:52:24.867Z'
Enter fullscreen mode Exit fullscreen mode

✅Date-Only Formats -return only Date

new Date().toDateString(); // 'Sun Nov 10 2024'
new Date().toLocaleDateString(); // '10/11/2024'
new Date().toLocaleDateString("en-US"); // '11/10/2024'
Enter fullscreen mode Exit fullscreen mode

5. Converting and Manipulating Dates
5.1 Testing Different Time Zones in Browser- Changing Time Zones Using Sensors

✅We already saw above that when you print new Date() on browser, you get date based on Timezone your browser is in. Mine is AEDT so you get AEDT timezone. But what if you want to test out different timezone. That's where “Sensors” come to rescue. I use edge browser in all of egamples below but you can use Chrome too.

✅Dev Tools → Sensors → Choose Timezone. For eg you can choose "Location" as "London" and you will see that browser runs in Greenwich Mean Time (GMT) though am based in Australia (AEDT).Observe above how time adjustments affect date outputs in JavaScript.

5.2 Changing Date Display Formats — Convert a date formatted with spaces or slashes to one separated by hyphens?

new Date().toLocaleDateString() // '10/11/2024'
new Date().toLocaleDateString().replace(/\//g,'-') // '10-11-2024'

// If date was in '10 Nov 2024' format, with space instead of /, use below
new Date().toLocaleString("en-GB",options).replace("/ /g","-") //'10-Nov-2024'
Enter fullscreen mode Exit fullscreen mode

5.3 Using getTime() to Retrieve Epoch Time

You can retrieve Epoch time from new Date().getTime() function OR using Date.now()

console.log(new Date().getTime()+ " ~~ " + Date.now())
//1731283520279 ~~ 1731283520279
Enter fullscreen mode Exit fullscreen mode

6. Advanced Date Handling Tips
6.1 Using new Date() vs Date()

When called with new, Date returns a Date object.
When called without new, it returns a string representation of the current date and time.

Date Constructor Options

6.2 Additional Locale Options for Date Formatting

1) const options = {
  day: "numeric",
  month: "short", //can also be long
  year: "numeric",
};
new Date().toLocaleString("en-GB",options);  //'9 Nov 2024'

2) const options = {
  day: "numeric",
  month: "short", //can also be long
  year: "numeric",
};
new Date().toLocaleString("en-GB",options);  //'9 November 2024'

3) //To display time, need to pass any time-related properties

const options = {
  day: "numeric",
  month: "short",
  year: "numeric",
  hour: "numeric",    // Add this to display the hour
  minute: "numeric",  // Add this to display the minute
  hour12: true        // Keeps time in 12-hour format
};

new Date().toLocaleString("en-GB",options)//'9 Nov 2024, 3:48 pm'
//3a) if hour12 was set to false, prints '9 Nov 2024, 15:38'
//3b) if year was set to 2-digit(instead of numeric') prints 
//    '10 Nov 24, 3:48 pm'

4) /* "day" option above,like year can also be "2-digit" or "numeric"
 - "numeric" - Displays the day as a number WITHOUT zero-padding 
               for single-digit days
 - "2-digit"- Will apply zero-padding for single-digit days
   */

 // Lets see numeric eg

const dayNumericOptions={
  day: "numeric",
  month: "short",
  year: "numeric"
}
//create a date with single digit day
new Date(2024,11,9).toLocaleString("en-GB",dayNumericOptions)//'9 Dec 2024'
// while if you passed "2-digit" to day and ran above prints '09 Dec 2024'

5) // Same way "minute" can be "numeric" or "2-digit".
   //Assume time is 3:05 pm and with "2-digit" option it will print "15:05"
   //while with numeric it will print "15:5"
Enter fullscreen mode Exit fullscreen mode

6.3 Creating Date Objects with Various Parameters

The Date constructor in JavaScript is flexible. It can accept 0 or > arguments → providing a range of ways to create Date objects

Date Construction Options

7. Summary

Handling dates in JavaScript is challenging due to varying time zones and formats. This article should help you cover everything you need to know about JavaScript date handling, from understanding UTC,ISO 8601 and locale time formats. Keep the reference image and code handy for quick access to date formatting options in your projects!

References — w3schools.com

Connect with Me
If you enjoyed this post and would like to stay updated with more content like this, feel free to connect with me on social media:

YouTube: Subscribe to my YouTube Channel for video tutorials and tons of videos on various subjects

Medium: Connect on Medium for blogs on various topic

Personal Website: My Website

Email: Email me on techspacedeck@gmail.com for any questions, comments, or just to say hi!
I appreciate your support and look forward to connecting with you! Happy coding! And Please do not forget to clap 👏

💖 💪 🙅 🚩
forthegeeks
Manjunath Shenoy

Posted on November 11, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related