Loading Now
Master Time Handling Effortlessly

JavaScript Date Objects: Master Time Handling Effortlessly

Share this content:

JavaScript offers powerful tools to work with dates and times, but few are as critical as the Date object. Whether you are new to JavaScript, or just immersing yourself at a greater depth, knowing how functionality with actual Date objects works will open up the capability of how to better implement it for your applications.

Angus writes: … So join me as we dive into all the ins and outs that make JavaScript Date objects unique, what their methods are, and why they are the preferred avenue for tackling dates and times for developers. By the end, you will see how easy it is to create and manipulate dates, also format them in a way the future you will appreciate.

1. What Is a JavaScript Date Object?

A Date object in JavaScript is basically, an object that represents a specific point in time. It is a native object that holds date and time in a way that you can work with and display with ease.

JavaScript keeps track of the date as the number of milliseconds that have elapsed since January 1, 1970 when you create a Date object.This is how JavaScript internally handles time – by calculating the milliseconds since that date.

Example:

const currentDate = new Date();
console.log(currentDate); // Outputs current date and time

2. Creating a Date Object

JavaScript offers various methods to generate Date objects and these can vary depending on your need.

a. Creating a Date for the Current Time:

To get the current date and time, create a new Date object with no arguments.

let today = new Date();
console.log(today);

b. Creating a Date from a String:

Although we can create a date object using a string representation of a date. It should look like “YYYY-MM-DD” in valid form.

let specificDate = new Date("2024-09-26");
console.log(specificDate);

c. Creating a Date by Providing Numbers:

Similarly you can pass numbers to Date object which will represent year, month, day, hour, minute and second.

let birthday = new Date(1996, 4, 12, 10, 30, 0); // May 12, 1996, 10:30 AM
console.log(birthday);

3. Common Methods of JavaScript Date Objects

Once you have a Date object created, you will likely want to do something more with the Date object e.g. you could manipulate it or retrieve data from it. JavaScript provides a ton of useful methods for this purpose:

a. getFullYear()

Returns the 4 digit year of a Date object (2024)

console.log(today.getFullYear()); // Outputs current year

b. getMonth()

Returns the month (0-11) Where January is 0 And December is 11

console.log(today.getMonth()); // Outputs current month

c. getDate()

Now, get the day of the month (from 1-31).

console.log(today.getDate()); // Outputs current day of the month

d. getDay()

This function gives you an indicator of day of the week [0–6] (0=Sunday, 6=Saturday)

console.log(today.getDay()); // Outputs current day of the week

e. getHours(), getMinutes(), getSeconds()

These methods will return hour, minute, second of current time.

console.log(today.getHours());   // Outputs current hour
console.log(today.getMinutes()); // Outputs current minute
console.log(today.getSeconds()); // Outputs current second

4. Manipulating JavaScript Date Objects

Date manipulation is a vital concept when dealing with time in Javascript, whether you are creating a calendar app or simply planning the work.

a. setFullYear(), setMonth(), setDate()

These are methods to change the year/month/day of an already existing Date obj.

birthday.setFullYear(2025);
console.log(birthday); // Outputs the updated year 2025

b. Adding Days or Time to a Date

Want to add or subtract days from a Date? You can simply modify the milliseconds of the Date object.

let tomorrow = new Date();
tomorrow.setDate(today.getDate() + 1); // Adds one day
console.log(tomorrow);

5. Formatting JavaScript Dates

JavaScript Date objects are great for manipulation but often need to be formatted for display purposes. The toLocaleDateString() method is handy for this.

Example:

let formattedDate = today.toLocaleDateString();
console.log(formattedDate); // Outputs the date in a readable format

If you want more control, toLocaleDateString() allows options like the following:

let options = { year: 'numeric', month: 'long', day: 'numeric' };
let formatted = today.toLocaleDateString('en-US', options);
console.log(formatted); // Outputs something like "September 26, 2024"

6. Comparing JavaScript Dates

Another useful application of the Date object is comparing two dates. Date objects can be compare in JavaScript using normal comparison operations (, =)

Example:

let date1 = new Date("2024-09-25");
let date2 = new Date("2024-09-26");

if (date1 < date2) {
  console.log("date1 is earlier than date2");
} else {
  console.log("date1 is later or the same as date2");
}

7. Timezones and UTC

By default, Date objects use the browser’s local timezone. JavaScript, on the other hand, allows you to use methods such as getUTCFullYear (), and getUTCHours () to deal with UTC (Coordinated Universal Time).

Example:

console.log(today.getUTCFullYear()); // Outputs the current year in UTC

Conclusion

Handling time and dates in web applications is easy with JavaScript Date objects. The Date object is an essential tool in any developer’s toolbox, whether you are creating and manipulating dates or formatting them for comparisons, there are all sorts of things to learn! You have already looked at the basics, so you can use JavaScript Date objects in your application for something like a countdown, calendar, and even for dynamic user notifications based on time, right?

With these skills in hand, you’re better equipped to control time within your JavaScript code – a powerful ability that opens up countless possibilities in web development!