Setter methods in JavaScript normal date and UTC date

Introduction :

Javascript Date has a lot of setter methods to manipulate different properties of a date object. You can easily change the year, hour, minute, milliseconds etc. of the date object using these methods. In this post, we will learn different setter methods with examples.

Javascript date setter methods :

Following are the setter methods available in Javascript Date :

1. setDate() :

This method is used to change the date of a Date object. For example :

var date = new Date();
console.log(date);
date.setDate(9);
console.log(date);

It will print the output like below :

2019-09-26T14:19:30.035Z
2019-09-09T14:19:30.035Z

2. setFullYear() :

Set the full year in four digits for a date.

var date = new Date();
console.log(date);
date.setFullYear(2011);
console.log(date);

Output :

2019-09-26T15:00:39.117Z
2011-09-26T15:00:39.117Z

3. setHours() :

This method is used to set the hours for a javascript Date. For example,

var date = new Date();
console.log(date);
date.setHours(11);
console.log(date.toLocaleTimeString());

Output :

2019-09-26T15:02:33.892Z
2019-09-26T06:02:33.892Z

It changes the local time. So, we are using toLocaleTimeString to print the time in local. The output will be like below :

2019-09-26T15:03:34.645Z
11:33:34 AM

4. setMilliseconds() :

Set the millisecond for a Date. This method changes the local time.

5. setMinutes() :

Change the minute for a Date in local time.

6. setMonth() :

Change the month for a Date. As like the other methods, it also works with the local time.

7. setSeconds() :

Change the seconds as per the local time.

8. setTime() :

Change the Date using an unix time, i.e. you can set number of milliseconds since January 1, 1970, 00:00:00 UTC. For prior times, negative number is used.

var date = new Date();
console.log(date);
date.setTime(1000);
console.log(date);

It will print :

2019-09-26T15:12:22.677Z 1970-01-01T00:00:01.000Z

9. setYear() :

Change the year using 2 or 3 digits as per the local time.

UTC setter methods in Javascript Date :

Similar to the above methods, Javascript Date also provides a couple of methods to work according to the universal time. Following are these methods :

1. setUTCDate()

2. setUTCFullYear()

3. setUTCHours()

4. setUTCMilliseconds()

5. setUTCMinutes()

6. setUTCMonth()

7. setUTCSeconds()

All of these methods work in a same way as like the other local time methods.