Saturday, November 17, 2018

JavaScript Set Date Methods

Set Date Methods

Set Date methods are used for setting a part of a date:

MethodDescription
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1, 1970)


The setFullYear() Method

The setFullYear() method sets the year of a date object. In this example to 2020:

<script>
var d = new Date();
d.setFullYear(2020);
document.getElementById("demo").innerHTML = d;
</script>

The setFullYear() method can optionally set month and day:

<script>
var d = new Date();
d.setFullYear(2020113);
document.getElementById("demo").innerHTML = d;
</script>

The setMonth() Method

The setMonth() method sets the month of a date object (0-11):

<script>
var d = new Date();
d.setMonth(11);
document.getElementById("demo").innerHTML = d;
</script>

The setDate() Method

The setDate() method sets the day of a date object (1-31):

<script>
var d = new Date();
d.setDate(20);
document.getElementById("demo").innerHTML = d;
</script>


The setDate() method can also be used to add days to a date:

<script>
var d = new Date();
d.setDate(d.getDate() + 50);
document.getElementById("demo").innerHTML = d;
</script>

The setHours() Method

The setHours() method sets the hours of a date object (0-23):

<script>
var d = new Date();
d.setHours(22);
document.getElementById("demo").innerHTML = d;
</script>

The setMinutes() Method

The setMinutes() method sets the minutes of a date object (0-59):

<script>
var d = new Date();
d.setMinutes(30);
document.getElementById("demo").innerHTML = d;
</script>

The setSeconds() Method

The setSeconds() method sets the seconds of a date object (0-59):

<script>
var d = new Date();
d.setSeconds(30);
document.getElementById("demo").innerHTML = d;
</script>

Compare Dates

Dates can easily be compared.
The following example compares today's date with January 14, 2100:

var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100014);

if (someday > today) {
    text = "Today is before January 14, 2100.";
else {
    text = "Today is after January 14, 2100.";
}
document.getElementById("demo").innerHTML = text;















































Share:

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *

Popular Posts

Blog Archive

Blog Archive

Hassan.mosmer1@gmail.com