Onjsdev

Share


JavaScript Date Object and Its Methods


By onjsdev

Jan 24th, 2024

The JavaScript Date object is a built-in object that represents a date and time. Let's dive into this object and its functional methods:

How To Create a JavaScript Date Object

You can create a date object with the current date and time using the new keyword followed by the Date() constructor.

const today = new Date();
console.log(today);
// Fri Mar 17 2023 22:11:09 GMT+0300 (GMT+03:00)

Alternatively, you can create a Date object with a specific date and time by passing the desired values to the Date() constructor.

const birthday = new Date(2000, 11, 25);
console.log(birthday);
Mon Dec 25 2000 00:00:00 GMT+0200 (GMT+03:00)

How To Work with Dates and Times

The Date object provides a wide range of methods and properties that allow us to work with dates and times.

Here are the most commonly used methods and properties:

// Get the current date and time
var today = new Date();

// Get the year
var year = today.getFullYear();

// Get the month (0-11)
var month = today.getMonth();

// Get the day of the month (1-31)
var day = today.getDate();

// Get the day of the week (0-6)
var dayOfWeek = today.getDay();

// Get the hours (0-23)
var hours = today.getHours();

// Get the minutes (0-59)
var minutes = today.getMinutes();

// Get the seconds (0-59)
var seconds = today.getSeconds();

// Get the milliseconds (0-999)
var milliseconds = today.getMilliseconds();

How To Format A Date and Time

Javascript date object formatting methods allow us to format dates and times in a wide range of formats, including ISO 8601, UTC and localized formats.

const today = new Date();
// Format the date as ISO 8601
const isoDateString = today.toISOString();
// 2023-03-17T19:17:01.978Z 3/17/2023

// Format the date as a string in the local timezone
const localDateString = today.toLocaleString();
// 10:17:01 PM 3/17/2023

How To Handle Timezones

It is important to handle times and dates based on different zones. The Date object provides methods for this purpose.

const today = new Date();

// Get the current UTC date and time
const utcDate = today.toUTCString();
// Fri, 17 Mar 2023 19:22:58 GMT 3/17/2023

// Format the date as a string in the specified timezone
const timezoneDateString = today.toLocaleString("en-US", {
  timeZone: "America/New_York",
});
// 3:22:58 PM

Conclusion

JavaScript provides a built-in Date object to work with dates and times. This object and its methods can be used get current date, handling timezone and formatting date and time.

Thank you for reading.