Computer >> Computer tutorials >  >> Programming >> Javascript

JavaScript Set Date Methods


The set date methods in JavaScript are −

MethodDescription
setDate()For setting the day as a number.
setFullYear()()For setting the year.
setHours()()For setting the hour.
setMilliseconds()For setting the milliseconds.
setMinutes()For setting the minutes.
setMonth()For setting the month.
setSeconds()For setting the seconds.
setTime()For setting the time.

Following is the code for the set Date methods −

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
</style>
</head>
<body>
<h1>JavaScript Set Date Methods</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to set Date and display it</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let date = new Date();
   document.querySelector(".Btn").addEventListener("click", () => {
      date.setHours(11);
      sampleEle.innerHTML = "setHours(11) = " + date + "<br>";
      date.setMonth(1);
      sampleEle.innerHTML += "setMonth(1) = " + date + "<br>";
      date.setMinutes(20);
      sampleEle.innerHTML += "setMinutes(20) = " + date + "<br>";
      date.setFullYear(1990);
      sampleEle.innerHTML += "setMinutes(1990) = " + date + "<br>";
   });
</script>
</body>
</html>

Output

JavaScript Set Date Methods

On clicking the “CLICK HERE” button −

JavaScript Set Date Methods