Friday, June 9, 2023

How to Get and Set the Day, Month, Year, or Time in JavaScript

How to Get and Set the Day, Month, Year, or Time in JavaScript

JavaScript has a Date object that you can use to store information about any point in time. Dates in JavaScript basically represent the total number of milliseconds that have passed since the "Unix epoch"—since the start of January 1, 1970, UTC.

In this tutorial, we will learn how to use the built-in methods of the Date object to get and set the day, month, year or time in JavaScript.

How to Get the Current Date and Time

Let's say you want to get the current date and time on a user's system. The easiest way to do that is to instantiate a new Date object using the Date() constructor without passing any parameters. Here is an example:

1
const today = new Date();
2
3
// Outputs: Date Fri Jun 02 2023 08:04:45 GMT+0530 (India Standard Time)

4
console.log(today); 

The above code gave us back a Date object that is now stored inside the variable today.

Another way of getting the current date and time involves simply calling the Date() function without the new keyword. This will return a string representation of the current date and time.

1
 const today = Date();
2
 
3
 // Outptus: Fri Jun 02 2023 07:44:26 GMT+0530 (India Standard Time)

4
 console.log(today);
5
 

The final result is similar to calling the toString() method on new Date() as shown below:

1
const today = new Date();
2
3
// Outputs: Fri Jun 02 2023 08:04:45 GMT+0530 (India Standard Time)

4
console.log(today.toString()); 

Get the Current Year

Let's say you only want to know the current year in JavaScript. You could extract that information from the above string. However, it is a lot easier to simply call the getFullYear() method. This method will return the year for the calling Date object according to local time.

1
const today = new Date();
2
3
// Outputs: 2023

4
console.log(today.getFullYear());

There is another method called getYear() but it is deprecated and you shouldn't use it. The getYear() method returns an integer that represents the current year according to local time, minus 1900. This method is deprecated and in the process of being removed.

Get the Current Month

You can use the getMonth() method of the Date object in order to get the current month for a particular Date instance. The returned month is an integer with a zero-based value.

1
const today = new Date();
2
3
// Outputs: Date Fri Jun 02 2023 08:53:09 GMT+0530 (India Standard Time)

4
console.log(today); 
5
6
// Outputs: 5

7
console.log(today.getMonth()); 

As you can see, we got back the number 5 when the current month was June.

Get the Current Day

You can get the current day of the week for a particular instance of the Date object by simply calling the getDay() method. This method will return an integer between 0 and 6 where 0 represents Sunday, 1 represents Monday and so on.

1
const today = new Date();
2
3
// Outputs: Date Fri Jun 02 2023 08:53:09 GMT+0530 (India Standard Time)

4
console.log(today); 
5
6
// Outputs: 5

7
console.log(today.getDay());

I got the value 5 back because it is Friday according to my local time.

Get the Current Date

Let's say you want to get the day of the month for a particular Date instance. You can use the getDate() method in this case. It will return a number between 1 and 31 representing the day of the month.

1
const today = new Date();
2
3
// Outputs: Date Fri Jun 02 2023 08:53:09 GMT+0530 (India Standard Time)

4
console.log(today); 
5
6
// Outputs: 2

7
console.log(today.getDate());

Get the Current Hour, Minute, or Second

There are three methods called getHours(), getMinutes(), and getSeconds() that you can use to get the hours, minutes, and seconds for a particular date respectively.

1
const today = new Date();
2
3
// Outputs: Date Fri Jun 02 2023 09:17:21 GMT+0530 (India Standard Time)

4
console.log(today); 
5
6
// Outputs: 9

7
console.log(today.getHours());
8
9
// Outouts: 17

10
console.log(today.getMinutes());
11
12
// Outputs: 21

13
console.log(today.getSeconds());

The hours go from 0 to 23. The minutes and seconds go from 0 to 59.

How to Set the Date and Time

There will be times when you will have to deal with a specific moment in time instead of the current time. JavaScript makes it possible for you to set your own date and time. Again, the easiest way to do that is with the Date() constructor.

The Date() constructor accepts different types of parameters such as a date string, a date object, or a bunch of integer values. A single integer value represents the timestamp or the number of milliseconds since midnight of January 1, 1970.

When you pass two integers to the constructor, they are considered the year and month respectively. You can pass five more optional parameters which represent the day, hour, minute, second, and millisecond. Any argument that you don't specify is automatically assigned the minimum possible value.

While it is possible for different implementations to support multiple string formats for specifying a date and time, you should consider sticking to the standard format below:

1
YYYY-MM-DDTHH:mm:ss.sssZ

Here is an example:

1
// Not All Platforms Might Support This Format

2
const party_a = new Date('10 June, 2023 09:30:00');
3
4
// Format Supported Across All Platforms

5
const party_b = new Date('2023-06-10T21:30:00.000');
6
7
// Set the Timezone to UTC

8
const party_c = new Date('2023-06-10T21:30:00.000Z');
9
10
// Outputs: Date Sat Jun 10 2023 09:30:00 GMT+0530 (India Standard Time)

11
console.log(party_a);
12
13
// Outputs: Date Sat Jun 10 2023 21:30:00 GMT+0530 (India Standard Time)

14
console.log(party_b);
15
16
// Outputs: Date Sun Jun 11 2023 03:00:00 GMT+0530 (India Standard Time)

17
console.log(party_c); 

We did not specify a timezone for our second date-time string. Therefore, its value was interpreted as local time. However, we did use Z in our third date-time string which implied that the time was in UTC. The return value in all the cases in still in local date and time.

How to Set the Year

You can use the setFullYear() method and pass it the year that you want to set as its first parameter. This method also accepts two more optional parameters which will represent the month and date value that you want to set respectively. The month is an integer with value ranging from 0 to 11. The date is also an integer and can have any value from 1 to 31.

Here are some examples:

1
const party = new Date('2023-06-10T21:30:00.000');
2
3
// Outputs: Date Sat Jun 10 2023 21:30:00 GMT+0530 (India Standard Time)

4
console.log(party);
5
6
party.setFullYear(2024);
7
8
// Outputs: Date Mon Jun 10 2024 21:30:00 GMT+0530 (India Standard Time)

9
console.log(party);
10
11
party.setFullYear(2024, 16, 12);
12
13
// Outputs: Date Mon May 12 2025 21:30:00 GMT+0530 (India Standard Time)

14
console.log(party); 

With the first call to setFullYear() we were able to change the year of our party.

The second call is more interesting as it sets the month to 16. However, there are only 12 months in a year. It is also important to note that the months are zero-based so December is represented by 11. The values wrap around to the next year once we reach December. There are now 5 months left, so the final month becomes May.

The date is set to 12 based on the value of the third parameter.

How to Set the Month

Similar to setFullYear(), you can use the setMonth() method to set both the month as well as the day of the month according to local time.

Overflowing values wrap around just like they did in the previous example:

1
const party = new Date('2023-06-10T21:30:00.000');
2
3
// Outputs: Date Sat Jun 10 2023 21:30:00 GMT+0530 (India Standard Time)

4
console.log(party);
5
6
party.setMonth(1);
7
8
// Outputs: Date Fri Feb 10 2023 21:30:00 GMT+0530 (India Standard Time)

9
console.log(party);
10
11
party.setMonth(1, 36);
12
13
// Outputs: Date Wed Mar 08 2023 21:30:00 GMT+0530 (India Standard Time)

14
console.log(party);

With a value of 1, the month is set to February because months are zero based. However, setting the date to 36 results in an overflow. Since there were only 28 days in February in 2023, the rest of the days are added to the month of March.

How to Set the Date or Day of the Month

The setDate() method is useful for setting the day of the month for the calling date. This method only accepts a single parameter which will update the day of the month. As usual, any overflow will get rolled over into the next month.

Here is an example:

1
const party = new Date('2023-06-10T21:30:00.000');
2
3
// Outputs: Date Sat Jun 10 2023 21:30:00 GMT+0530 (India Standard Time)

4
console.log(party);
5
6
party.setDate(33);
7
8
// Outputs: Date Mon Jul 03 2023 21:30:00 GMT+0530 (India Standard Time)

9
console.log(party);

June has 30 days. Therefore, setting the value of date to 33 results in an overflow and the actual date become July 3.

How to Set the Hour, Minute and Second

You can use methods like setHours(), setMinutes(), setSeconds(), and setMilliseconds() to set the value for hours, minutes, seconds, and milliseconds respectively.

Similar to the setFullYear() method, the setHours() method is also useful for setting the values of smaller units of time like minutes, seconds, and milliseconds. Here are some examples:

1
const party = new Date('2023-06-10T21:30:00.000');
2
3
// Outputs: Date Sat Jun 10 2023 21:30:00 GMT+0530 (India Standard Time)

4
console.log(party);
5
6
party.setHours(12);
7
8
// Outputs: Date Sat Jun 10 2023 12:30:00 GMT+0530 (India Standard Time)

9
console.log(party);
10
11
party.setHours(12, 102, 53);
12
13
// Outputs: Date Sat Jun 10 2023 13:42:53 GMT+0530 (India Standard Time)

14
console.log(party);
15
16
party.setMinutes(36, 53);
17
18
// Outputs: Date Sat Jun 10 2023 13:36:53 GMT+0530 (India Standard Time)

19
console.log(party); 
20
21
party.setSeconds(153);
22
23
// Outputs: Date Sat Jun 10 2023 13:38:33 GMT+0530 (India Standard Time)

24
console.log(party);

The first output is based on the provided date. In the next one, we simply set the hours to 12 without changing anything else. Our next statement, sets the hours to 12 but the minutes to 102. Since there is an overflow, the hours become 13 and the minutes become 42.

After that, we set the minutes to 36 and the seconds to 53. The hours stay at 13 due to our earlier statement. Our final statement sets the seconds for our Date object. However, there is an overflow so the minutes increase by 2 and the seconds become 33.

Final Thoughts

In this tutorial, we learned the basics of getting and setting different values of the Date object using built-in methods. You should now be able to get the year, month, days, hours, minutes, or seconds of any date in JavaScript. Similarly, you will be able to set these values without getting confused due to any overflow.


No comments:

Post a Comment