The Date Object and its Methods in JavaScript


  In JavaScript, the Date object is used to work with dates and times. You can create date instances and use methods to get and set various parts of the date, such as the year, month, day, hour, minute, second, among others.


Syntax:


  To create a date instance in JavaScript, use the following syntax:

  • `const fecha = new Date();` – Creates a new date with the current date and time.

  • `const fecha = new Date("2024-12-09");` – Creates a new date with a specific date.

  Some of the available methods of the Date object include:

  • getFullYear() Returns the year of the date.

  • getMonth() Returns the month of the date (0-11).

  • getDate() Returns the day of the month of a date (1-31).

  • setHours() Sets the hours of the date.

  • getDay() Returns the day of the week (0-6), where 0 is Sunday and 6 is Saturday.

  • getTime() Returns the number of milliseconds since January 1, 1970.

  • setFullYear() Sets the year of the date.

  • setMonth() Sets the month of the date (0-11).

  • setDate() Sets the day of the month (1-31).

Examples:

`getFullYear()`

const fecha = new Date();
console.log(fecha.getFullYear());  // Example: 2024

Explanation:

The getFullYear() method returns the year of the date. In this case, if the current date is "2024", the method will return 2024.

`getDate()`

const fecha = new Date();
console.log(fecha.getDate());  // Example: 10 (current day)

Explanation:

The getDate() method returns the day of the month of the date. In this example, if the date is December 10th, the value will be 10.

`getDay()`

const fecha = new Date();
console.log(fecha.getDay());  // Example: 1 (Monday)

Explanation:

The getDay() method returns the day of the week (0-6), where 0 is Sunday and 6 is Saturday. In this example, if the date is a Monday, it will return 1.


Purpose:

  • Manipulate dates and times in your JavaScript applications.
  • Extract specific parts of a date, such as the year or month.
  • Perform date calculations or comparisons.

Exercises


The rest of the content is available only for registered and premium users!



Which method is used to get the month of a date?



JavaScript Concepts and Reference

What is an object method in JavaScript? Which JavaScript object works with dates? What does the date function do? How to use the date data type? javascript current date dd/mm/yyyy Date javascript format date javascript dd/mm/yyyy New Date JavaScript Subtract dates JavaScript Current date JavaScript date-fns