new date javascript

New Date JavaScript

If you're building a website or web application that requires the current date or time, JavaScript has you covered with the Date object. This object provides various methods for working with dates and times.

Creating a New Date

To create a new instance of the Date object, simply call the constructor without any arguments:


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

This will create a new Date object set to the current date and time.

Working with Dates and Times

The Date object provides several methods for working with dates and times. Here are a few examples:

  • getFullYear(): Returns the year (4 digits) of the specified date
  • getMonth(): Returns the month (0-11) in the specified date
  • getDate(): Returns the day of the month (1-31) for the specified date
  • getDay(): Returns the day of the week (0-6) for the specified date
  • getHours(): Returns the hour (0-23) in the specified date
  • getMinutes(): Returns the minutes (0-59) in the specified date
  • getSeconds(): Returns the seconds (0-59) in the specified date
  • getTime(): Returns the number of milliseconds since January 1, 1970, 00:00:00 UTC

Here's an example of using the getMonth() method:


let currentDate = new Date();
let currentMonth = currentDate.getMonth();
console.log(currentMonth);

This will output the current month (0-11) to the console.

Formatting Dates and Times

The Date object also provides several methods for formatting dates and times. Here are a few examples:

  • toDateString(): Returns the date portion of the specified date as a human-readable string
  • toLocaleDateString(): Returns a localized string representing the date portion of the specified date
  • toLocaleTimeString(): Returns a localized string representing the time portion of the specified date
  • toTimeString(): Returns the time portion of the specified date as a human-readable string

Here's an example of using the toDateString() method:


let currentDate = new Date();
let dateString = currentDate.toDateString();
console.log(dateString);

This will output the current date as a human-readable string to the console.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe