DEV Community

Shadrack
Shadrack

Posted on

A Guide to Date and Time in Javascript

Introduction

Time and date manipulation is notoriously challenging. Consequently, developers encountering time zone rules, leap seconds, differences in locale-specific formatting are wise to resort to popular time and date manipulation libraries. Still, without understanding how exactly they work, it’s still easy to create all sorts of obscure bugs.
So, as developers, we need to know how to compute date and time. JavaScript, the world’s most popular programming language, has plenty of helpful APIs, but they can throw up complications if you’ve never used them before.
In this article we’re going to look into JavaScript Date, a standard built-in object for computing date and time. We’ll look at the issue of formatting, and dive deep into its related aspects.
We’ll also look at the different use cases for JavaScript dates in programming, so we can see the challenges, as well as the benefits, in action.

Date Object

A JavaScript date defines the epoch that represents milliseconds since midnight at the beginning of 1 January 1970 UTC(Coordinated Universal Time). The term epoch refers to a particular point in time that happened in history, and is our 'Big Bang' moment. The Date object is a built-in object in that allows us to format and manipulate date and time representing a specific moment in time.

Creating Date Objects
In Javascript, you can create a Date object in four different ways namely:

  • Using the new Date() constructor
  • Passing individual Date components
  • Passing string to a javascript Date
  • Using Timestamps new Date() The most common way to create a Date object is using the new Date() constructor. This returns the current date and time within the local timezone. This article is being written on Tuesday, September 24th in Kenya(EAT), so that is the current date, time and timezone that is represented below:

// set variable to current date and time
const now = new Date();

// View the output
console.log(now)

Enter fullscreen mode Exit fullscreen mode

Output:

Tue Sep 24 2024 14:19:01 GMT+0300 (East Africa Time)
Enter fullscreen mode Exit fullscreen mode

Passing Individual Date Components
You can create a Date object by passing individual date and time components (year, month, day, hour, minute, second, and millisecond) as arguments to the constructor.

/**
 Let's understand the arguments passed.
 Starting from the left to right,
   - 2024 represents the Year
   - 8 represents the Month. It is an index value that starts 
     with 0 which represents January month in the English
     calendar, 1 for February, and so on.
   - 10 represents the day between 1 to 31.
   - 23 represents the hour between 1 to 24.
   - 15 represents the minute.
   - 34 represents the second.
   - 0 represent the millisecond.

*/
const date = new Date(2024, 8, 10, 23, 15, 34, 0);
console.log(date);
Enter fullscreen mode Exit fullscreen mode

Output:

`Sun Sep 10 2024 23:15:34 GMT+0530 (East Africa Time)`
Enter fullscreen mode Exit fullscreen mode

However, as the arguments are optional, one must be mindful of how the Date constructor behaves when we omit one or more arguments.

// Omitted seconds and milliseconds
console.log(new Date(2023, 8, 10, 23, 15)); // Sun Sep 10 2023 23:15:00

// Omitted hour, minute, seconds and milliseconds
console.log(new Date(2023, 8, 10)); // Sun Sep 10 2023 00:00:00

// Passed only Year and Month
console.log(new Date(2023, 8)); // Fri Sep 01 2023 00:00:00

// Attention Please!!!
console.log(new Date(2023)); // Thu Jan 01 1970 05:30:02
Enter fullscreen mode Exit fullscreen mode

Parsing string to a Javascript Date

const date = new Date("2013-09-10T13:24:00");
console.log(date); // Tue Sep 10 2013 13:24:00 GMT+0530 (India Standard Time)
Enter fullscreen mode Exit fullscreen mode

Using Timestamps
Alternatively, a Date Object can be created by passing a timestamp, representing the total number of milliseconds or seconds, since the epoch time(January 1, 1970)

const date = new Date(1688737100000);
console.log(date); // Fri Jul 07 2023 16:8:20 GMT+0300 (East Africa Time)
Enter fullscreen mode Exit fullscreen mode

Current Date Using Javascript Date Methods
With the Date Object, we can use methods like getFullYear(), getMonth(), and getDate() to get the current year, month, and date, respectively.

const date = new Date();

date.getFullYear(); // 2024
date.getMonth(); // 9
date.getDate(); // 24

Enter fullscreen mode Exit fullscreen mode

We can now combine these methods to form the current date representation.

const date = new Date();

const day = date.getDate();
const month = date.getMonth() + 1; // The month index starts from 0
const year = date.getFullYear();

let currentDate = `${day}/${month}/${year}`;
console.log(currentDate); // 24/9/2024
Enter fullscreen mode Exit fullscreen mode

Autocorrection in Date Object
When you assign out of range values in the Date object, it auto-corrects itself.

const date = new Date(2024, 0, 33);
// Jan does not have 33 days

console.log(date);
Enter fullscreen mode Exit fullscreen mode

Output:

Tue Sep 24 2024
Enter fullscreen mode Exit fullscreen mode

Conclusion

Knowing how to work with dates is essential for many common tasks in Javascript, as this can enable you do many tasks from setting up a repeating report to display dates and schedules in the correct time zone.
In this article, we learned how to create an instance of the Date object, and use its in-built methods to access and modify components of a specific date.

Top comments (0)