Basics

JS Dates

Working with JavaScript Dates

JavaScript dates use Date objects, handling timezones cautiously.

Creating Date Objects

In JavaScript, dates are handled using the Date object. You can create a new Date object using the new Date() constructor. There are several ways to initialize a date object, including:

  • Without arguments, creating a date with the current date and time.
  • With a date string.
  • With date and time components as numbers.

Date Methods

The Date object provides numerous methods for getting and setting date values:

  • getFullYear() - Returns the year.
  • getMonth() - Returns the month (0-11).
  • getDate() - Returns the day of the month (1-31).
  • getDay() - Returns the day of the week (0-6).
  • getHours(), getMinutes(), getSeconds() - Return the respective time components.

Handling Timezones

JavaScript handles timezones using the local timezone of the environment where the script is executed. The Date object automatically adjusts for daylight saving time and other timezone quirks.

To handle timezones explicitly, consider using the Date methods that deal with UTC, such as getUTCHours(), getUTCMinutes(), etc., or leverage libraries like Moment.js or date-fns for more complex timezone manipulations.

Formatting Dates

JavaScript offers limited built-in options for formatting dates. The toLocaleDateString() and toLocaleTimeString() methods allow you to format dates and times according to the user's locale, providing a more human-readable format.

Next
Math