Loading...

How To Get Current Date In JavaScript – Complete Guide

How To Get Current Date In JavaScript – Complete Guide

JavaScript is a powerful and versatile programming language that has become a staple for web development. One of the many features JavaScript offers is the ability to work with date and time. In this blog post, we will explore different ways to get the current date in JavaScript, and we will also take a look at the popular library Day.js for handling dates.

Introduction to JavaScript Date Object

JavaScript has a built-in Date object that can be used to represent dates and times. It comes with a set of methods and properties that allow you to perform various operations like getting the current date, comparing dates, or formatting dates. Let's start by creating a new Date object to represent the current date and time:

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

The new Date() constructor without any arguments creates a new Date object representing the current date and time.

Get the Current Date

Now that we have a Date object representing the current date and time, let's extract the date information from it. We will be using various methods provided by the Date object to get the date components.

Get the Current Day, Month, and Year

To get the current day, month, and year, we can use the following methods:

  • getDate(): Returns the day of the month (1-31) for the specified date.
  • getMonth(): Returns the month (0-11) for the specified date, where 0 corresponds to January, 1 to February, and so on.
  • getFullYear(): Returns the year (4 digits) for the specified date.

Here's an example:

const currentDate = new Date(); const day = currentDate.getDate(); const month = currentDate.getMonth() + 1; // Add 1 as months are zero-based const year = currentDate.getFullYear(); console.log(`Today's date is ${day}-${month}-${year}`);

Get the Current Day of the Week

To get the current day of the week, we can use the getDay() method, which returns the day of the week (0-6) for the specified date, where 0 corresponds to Sunday, 1 to Monday, and so on. Here's an example:

const currentDate = new Date(); const dayOfWeek = currentDate.getDay(); console.log(`Today is day ${dayOfWeek} of the week.`);

If you want to display the day of the week as a string (e.g., "Monday"), you can use an array of day names and get the corresponding name using the dayOfWeek index:

const currentDate = new Date(); const dayOfWeek = currentDate.getDay(); const dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; console.log(`Today is ${dayNames[dayOfWeek]}.`);

Formatting the Current Date

Sometimes, you might want to display the current date in a specific format. JavaScript provides several methods to help you with this task.

Using toLocaleDateString()

The toLocaleDateString() method returns a string with a language-sensitive representation of the date portion of the specified Date object. It takes two optional parameters: the locale and an object with formatting options.

Here's an example:

const currentDate = new Date(); const formattedDate = currentDate.toLocaleDateString('en-US', { day: '2-digit', month: 'long', year: 'numeric', }); console.log(`Today's date is ${formattedDate}`);

In this example, we used the en-US locale and specified that we want a 2-digit day, a long month name, and a numeric year.

Using Intl.DateTimeFormat()

Another option for formatting dates is the Intl.DateTimeFormat object, which provides language-sensitive date and time formatting. Here's an example:

const currentDate = new Date(); const dateFormatter = new Intl.DateTimeFormat('en-US', { day: '2-digit', month: 'long', year: 'numeric', }); const formattedDate = dateFormatter.format(currentDate); console.log(`Today's date is ${formattedDate}`);

This example produces the same output as the previous one, but it uses the Intl.DateTimeFormat object to format the date.

Working with Day.js

Day.js is a popular JavaScript date library that offers a lightweight and easy-to-use API to work with dates. It's also immutable, which means that it doesn't modify the original Date object, making it a safer choice for handling dates.

To get started with Day.js, you need to include it in your project:

<script src="https://cdn.jsdelivr.net/npm/dayjs/dayjs.min.js"></script>

Now, let's see how to get the current date using Day.js:

const currentDate = dayjs(); console.log(currentDate.toString());

To format the current date using Day.js, you can use the format() method:

const currentDate = dayjs(); const formattedDate = currentDate.format('DD-MMMM-YYYY'); console.log(`Today's date is ${formattedDate}`);

In this example, we used the format string 'DD-MMMM-YYYY', which corresponds to a 2-digit day, a long month name, and a 4-digit year.

FAQ

1. How do I get the current time in JavaScript?

To get the current time, you can use the following methods on a Date object:

  • getHours(): Returns the hour (0-23) for the specified date.
  • getMinutes(): Returns the minutes (0-59) for the specified date.
  • getSeconds(): Returns the seconds (0-59) for the specified date.

Here's an example:

const currentDate = new Date(); const hours = currentDate.getHours(); const minutes = currentDate.getMinutes(); const seconds = currentDate.getSeconds(); console.log(`The current time is ${hours}:${minutes}:${seconds}`);

2. How do I compare dates in JavaScript?

To compare dates, you can convert the Date objects to timestamps (milliseconds since January 1, 1970) using the getTime() method or by using the valueOf() method, and then compare the timestamps:

const date1 = new Date('2021-01-01'); const date2 = new Date('2021-12-31'); if (date1.getTime() < date2.getTime()) { console.log('Date1 is earlier than Date2'); } else if (date1.getTime() > date2.getTime()) { console.log('Date1 is later than Date2'); } else { console.log('Date1 and Date2 are the same'); }

3. How do I add or subtract days, months, or years to a date?

With Day.js, you can easily add or subtract days, months, or years to a date using the add() and subtract() methods. Here's an example:

const currentDate = dayjs(); const newDate = currentDate.add(7, 'day'); // Add 7 days console.log(newDate.toString());

In this example, we added 7 days to the current date using the add() method. You can also use 'month' or 'year' as the second argument to add or subtract months or years.

That's it! Now you know various ways to get the current date in JavaScript and how to work with dates using the built-in Date object and the popular Day.js library. Keep exploring and happy coding!

Sharing is caring

Did you like what Vishnupriya wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far