JavaScript - tutorial - 13 - time and date

revision:


Content

JavaScript timing events "get" date methods: pulling date and time values new Date() constructor "set" date methods: set part of a date date methods time zones time and date examples


JavaScript timing events

top

JavaScript can be executed in time-intervals. This is called timing events. The window object allows execution of code at specified time intervals.

The two key methods to use with JavaScript are:

1/ setTimeout(function, milliseconds): executes a function, after waiting a specified number of milliseconds;
2/ setInterval(function, milliseconds): same as setTimeout(), but repeats the execution of the function continuously.

The setTimeout() and setInterval() are both methods of the HTML DOM Window object.

Timing events are:

window.setTimeout(function, milliseconds): the method can be written without the window prefix. The first parameter is a function to be executed. The second parameter indicates the number of milliseconds before execution.

window.clearTimeout(timeoutVariable): this method stops the execution of the function specified in setTimeout() and can be written without the window prefix. The method uses the variable returned from setTimeout(): myVar = setTimeout(function, milliseconds); clearTimeout(myVar). If the function has not already been executed, you can stop the execution by calling the clearTimeout() method.

window.setInterval(function, milliseconds): the method repeats a given function at every given time-interval. The method can be written without the window prefix. The first parameter is the function to be executed. The second parameter indicates the length of the time-interval between each execution.

window.clearInterval(timerVariable): this method stops the executions of the function specified in the setInterval() method. The method can be written without the window prefix. The clearInterval() method uses the variable returned from setInterval(): myVar = setInterval(function, milliseconds); clearInterval(myVar);.

Examles: timing events

setTimeout()

Click "try it". Wait 3 seconds, and the page will alert "Hello".

setTimeout() - clearTimeout()

setTimeout() - clearTimeout()

Click "try it". Wait 3 seconds; the page will alert "Hi, there!".

Click "Stop" to prevent the first function to execute.

(You must click "Stop" before the 3 seconds are up.)

setInterval

This example executes a function called "myTimer" once every second (like a digital watch).

clearInterval()

A script on this page starts this clock:

code:
                <div>
                    <p>setTimeout()</p>
                    <p class="spec">Click "try it". Wait 3 seconds, and the page will alert "Hello".</p>
                    <button onclick="setTimeout(myFunction, 3000);">Try it</button>         
                    <p id="time1" style="color: red;" class="spec-2"></p>
                </div>
                <p>setTimeout() - clearTimeout()</p>
                <div class="spec">
                      <p>setTimeout() - clearTimeout()</p>
                    <p>Click "try it". Wait 3 seconds; the page will alert "Hi, there!".</p>
                    <p>Click "Stop" to prevent the first function to execute.</p>
                    <p>(You must click "Stop" before the 3 seconds are up.)</p>
                    <button onclick="myVar = setTimeout(timeFunction, 3000)">Try it</button>
                    <button onclick="clearTimeout(myVar)">Stop it</button>  
                    <p id="time2" style="color: blue;" class="spec"></p>
                </div>
                <p>setInterval</p>
                <div>
                    <p class="spec">This example executes a function called "myTimer" once every second (like a digital watch).</p>      
                    <p id="time3" class="spec"></p> 
                </div> 
                <p>clearInterval()</p> 
                <div>
                    <p class="spec">A script on this page starts this clock:</p>
                    <p  class="spec" id="time4"></p>
                    <button onclick="clearInterval(timingVar)">Stop time</button>
                </div>
            </div>
            <script>
                function myFunction() {
                    // alert('Hello');
                   document.getElementById("time1").innerHTML = "Hello";
                }
                function timeFunction() {
                    // alert("Hi, there!");
                    document.getElementById("time2").innerHTML = "Hi, there!";
                }
                var timeVar = setInterval(myTimer, 1000);
                    function myTimer() {
                        var d = new Date();
                        document.getElementById("time3").innerHTML = d.toLocaleTimeString();
                }
                var timingVar = setInterval(myTimer1 ,1000);
                    function myTimer1() {
                        var d = new Date();
                        document.getElementById("time4").innerHTML = d.toLocaleTimeString();
                    }
            </script>
            

check if the provided day is a weekday.

Using below methods, you'll be able to check if the date that you provide in the function is either a weekday or weekend day.

Example - code

                const isWeekday = (date) => date.getDay() % 6 !== 0;
                console.log(isWeekday(new Date(2021, 0, 11))); 
                // Result: true (Monday)
            
                const isWeekday = (date) => date.getDay() % 6 !== 0;
                console.log(isWeekday(new Date(2021, 0, 10))); 
                // Result: false (Sunday)
            
                const isWeekend = (date) => [0, 6]. indexOf(date.getDay()) !== -1;
                console.log(isWeekend(new Date(2021, 4, 14)));
                // false (Friday)
            

"get" date methods: pulling date and time values

top

"get" date methods are:

Date.now() : returns the number of milliseconds since January 1, 1970 00:00:00 UTC.

getDate() : Date.getDate(): get the day of the month as a number (1-31);

getDay() : Date.getDay() : returns the weekday of a date as a number (0-6).

In JavaScript, the first day of the week (0) means "Sunday", even if some countries in the world consider the first day of the week to be "Monday". You can use an array of names, and getDay() to return the weekday as a name.

getFullYear() : Date.getFullYear(): returns the year of a date as a four digit number (yyyy).

getHours() : Date.getHours(): returns the hours of a date as a number (0-23)

getMilliseconds() : Date.getMilliseconds() : returns the milliseconds of a date as a number (0-999)

getMinutes() : Date.getMinutes() : returns the minutes of a date as a number (0-59).

getMonth() : Date.getMonth() : returns the month of a date as a number (0-11).

In JavaScript, the first month (January) is month number 0, so December returns month number 11. You can use an array of names, and getMonth() to return the month as a name.

getSeconds() : Date.getSeconds(): returns the seconds (0 to 59) of a date.

getTime() : Date.getTime() : returns the number of milliseconds since January 1, 1970.

etUTCDate() : Date.getUTCDate() : the day (date) of the month in the specified date according to universal time.

Also available for day, month, fullyear, hours, minutes etc.

Examples:

This example takes 2 seconds to run




Days and weeks













click the button here below to display today's day of the month.



Click the button to display today's day of the week.






Months and years

Click the button to display the full year of today's date.




Click the button to display the number that represents this month.

0 = January, 1 = February, etc.






Hours and minutes and (milli)second

Click the button to display the hour of the time right now.





Click the button to display the milliseconds of the time right now.



Click the button to display the minuites of the time right now.








code:
                    <div class="spec">
                        <a id="datum1"></a>
                        <div>
                            <p> This example takes 2 seconds to run</p>
                            <button onclick="timeNow()">run</button><br>
                            <a id="datum2" class="spec"></a><br>
                            <a id="datum3" class="spec"></a><br>
                        </div>
                        <p>Days and weeks</p>
                        <div>
                            <a id="datum4" class="spec"></a><br>
                            <a id="datum5" class="spec"></a><br>
                            <a id="datum6" class="spec"></a><br>
                            <a class="spec" id="datum7"></a><br><br>
                            <a class="spec" id="datum8"></a><br>
                            <a class="spec" id="datum9"></a><br><br> 
                            <button onclick="today_a()">run</button><br><br>
                            <a class="spec" id="datum10"></a><br><br>    
                            <p class="spec">click the button here below to display today's day of the month.</p>
                            <button onclick="todaysDay()">today</button><br>
                            <a class="spec" id="datum11"></a><br>   
                            <p>Click the button to display today's day of the week.</p>
                            <button onclick="weekDay()">click me</button><br><br>
                            <a class="spec" id="datum12"></a><br>   
                            <button onclick="weekDay1()">day of week</button><br>
                            <a class="spec" id="datum13"></a><br>   
                        </div>
                        <p>Months and years</p>
                        <div class="spec">
                            <p>Click the button to display the full year of today's date.</p>
                            <button onclick="thisYear()">this year</button><br><br>
                            <a class="spec" id="datum14"></a><br>  
                            <p>Click the button to display the number that represents this month.</p>
                            <p>0 = January, 1 = February, etc.</p>
                            <button onclick="thisMonth()">this month</button><br>
                            <a class="spec" id="datum15"></a><br> 
                            <a class="spec" id="datum16"></a><br> 
                            <a class="spec" id="datum17"></a><br>   
                            <a class="spec" id="datum18"></a><br>   
                        </div>
                        <p>Hours and minutes and (milli)second</p>
                        <div class="spec">
                            <p>Click the button to display the hour of the time right now.</p>
                            <button onclick="theHours()">get the hours</button><br>
                            <a class="spec" id="datum19"></a><br>   
                            <a class="spec" id="datum20"></a><br>   
                            <a class="spec" id="datum21"></a><br>  
                            <p>Click the button to display the milliseconds of the time right now.</p>
                            <button onclick="milliSeconds()">get milliseconds</button><br> 
                            <a class="spec" id="datum22"></a><br> 
                            <p>Click the button to display the minuites of the time right now.</p>
                            <button onclick="thisMinute()">this minute</button><br><br>
                            <a class="spec" id="datum23"></a><br> 
                            <a class="spec" id="datum24"></a><br>
                            <a class="spec" id="datum25"></a><br> 
                            <a class="spec" id="datum26"></a><br> 
                            <a class="spec" id="datum27"></a><br> 
        
                        </div>
                    
                    </div>
                    <script>
                        var today = new Date();
                        var date1 = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
                        var time1 = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
                        var dateTime = date1 +' '+ time1;
                        document.getElementById("datum1").innerHTML = "Current date and time: " + dateTime;
                        
                        function timeNow(){
                            const start = Date.now();
                            document.getElementById("datum2").innerHTML = "starting timer";
                            setTimeout(() => {
                                const millis = Date.now() - start;
                                document.getElementById("datum3").innerHTML = (`seconds elapsed = ${Math.floor(millis / 1000)} seconds`);
                            }, 2000);
                        }
                        //days and weeks
                        var d = new Date();
                        document.getElementById("datum4").innerHTML = "day of month: " + d.getDate();
                        document.getElementById("datum5").innerHTML = "day of month: " + new Date().getDate();
                        document.getElementById("datum6").innerHTML = "weekday: " + d.getDay();
                        document.getElementById("datum7").innerHTML = "weekday: " + new Date().getDay();
                        var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
                        document.getElementById("datum8").innerHTML = "weekday: " + days[d.getDay()];
                        document.getElementById("datum9").innerText = "weekday: " + days[new Date().getDay()];
                                       
                        function today_a(){
                            let currentDate = new Date();
                            let cDay = currentDate.getDate();
                            let cMonth = currentDate.getMonth() + 1;
                            let cYear = currentDate.getFullYear();
                            document.getElementById("datum10").innerHTML = "today's date: " + "<b>" + cDay + "/" + cMonth + "/" + cYear + "</b>";
                        }
                        function todaysDay() {
                            var d = new Date();
                            var n = d.getDate();
                            document.getElementById("datum11").innerHTML = " today is " + n +"th day of the month";;
                        }
                       
                        function weekDay() {
                            var d = new Date();
                            var weekday = new Array(7);
                            weekday[0] = "Sunday";
                            weekday[1] = "Monday";
                            weekday[2] = "Tuesday";
                            weekday[3] = "Wednesday";
                            weekday[4] = "Thursday";
                            weekday[5] = "Friday";
                            weekday[6] = "Saturday";
        
                            var n = weekday[d.getDay()];
                            document.getElementById("datum12").innerHTML = "today is " + n;
                        }
        
                        function weekDay1() {
                            var d = new Date();
                            var n = d.getDay();
                            document.getElementById("datum13").innerHTML = "today is the " + n +"th/rd day of the week";
                        }
        
                        // months and years
                        function thisYear(){
                            var d = new Date();
                            document.getElementById("datum14").innerHTML = "this year is " + d.getFullYear();
                        }
                        function thisMonth() {
                            var d = new Date();
                            var n = d.getMonth();
                            document.getElementById("datum15").innerHTML = "the number of this month: " + n;
                            document.getElementById("datum16").innerHTML =  "the number of the month: " + d.getMonth();    
                        }
        
                        var d = new Date();
        
                        var months = ["January","February","March","April","May","June","July","August","September","October",
                        "November","December"];
                        document.getElementById("datum17").innerHTML =  "this month is: " + months[d.getMonth()];
                        document.getElementById("datum18").innerHTML =  "this month is " + months[new Date().getMonth()];
                    
                    // hours, minutes and seconds
                        function theHours() {
                            var d = new Date();
                            var n = d.getHours();
                            document.getElementById("datum19").innerHTML = "it is now " +n + "hour(s)";
                        }
                       
                        var d = new Date();
                        document.getElementById("datum20").innerHTML = "Hours: " + d.getHours();
                        document.getElementById("datum21").textContent = "Hours: " + new Date().getHours();
        
                        function milliSeconds() {
                            var d = new Date();
                            var n = d.getMilliseconds();
                            document.getElementById("datum22").innerHTML = n + " milliseconds";
                        }
        
                        function thisMinute() {
                            var d = new Date();
                            var n = d.getMinutes();
                            document.getElementById("datum23").innerHTML = n + " minutes";
                        }
        
                        var d = new Date();
                        document.getElementById("datum24").innerHTML =  "Minutes: " + d.getMinutes();      
                        document.getElementById("datum25").innerHTML =  "Seconds: " + d.getSeconds();
                        document.getElementById("datum26").innerHTML =  "Milliseconds since 1970/1/1: " + d.getTime();
                        document.getElementById("datum27").innerHTML =  "UTC date: " +  d.toUTCString();
                    </script>
                

parse : parses a string representation of a date, and returns the number of milliseconds since January 1, 1970

Examples: parse

code:
                <div class="spec">
                    <a id="datum28"></a>
                </div>
                <script>
                    var d = Date.parse("April 20, 2024);
                    document.getElementById("datum28").innerHTML = d;
                </script>
            

new Date() constructor

top

By default, JavaScript will use the browser's time zone and display a date as a full text string. Date objects are created with the new Date() constructor.

JavaScript counts months from 0 to 11. January is 0. December is 11. The internal clock in JavaScript starts at midnight January 1, 1970.

Examples: internal clock

click the button to display the current date and number of milliseconds since midnight, January 1, 1970.




click the button to display the current date and calculate the number of years since midnight, January 1, 1970.



code:
                <div class="spec">
                    <p class="spec">click the button to display the current date and number of milliseconds since midnight, 
                    January 1, 1970.</p>
                    <button onclick="tijd()">try it</button><br><br>
                    <a  class="spec" id="datum29"></a><br>
                    <p class="spec">click the button to display the current date and calculate the number of years since midnight, 
                    January 1, 1970.</p>
                    <button onclick="jaren()">try it</button><br><br>
                    <a  class="spec" id="datum30"></a>    
                </div>
                <script>
                    function tijd() {
                        var d = new Date();
                        var n = d.getTime();
                        document.getElementById("datum29").innerHTML = (d + ", - , " + n) + " milliseconds";
                    }
                    function jaren() {
                        var minutes = 1000 * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var d = new Date();
                        var t= d.getTime();
                        var y = Math.round(t / years);
                        document.getElementById("datum30").innerHTML = ( d + "<br> " + y + " years");
                    }
                </script>
            

new Date() constructor

new Date() : creates a new date object with the current date and time.

new Date(year, month, day, hour, minute, second, millisecond) : create a custom date object with a specific date and time.

You can omit anything you want except for year and month.


6 numbers specify year, month, day, hour, minute, second.
5 numbers specify year, month, day, hour, and minute.
4 numbers specify year, month, day, and hour.
3 numbers specify year, month, and day.
2 numbers specify year and month.

Note: you cannot omit month. If you supply only one parameter it will be treated as milliseconds. Also, one and two digit years will be interpreted as 19xx.

new Date(dateString) : creates a new date object from a date string.

new Date(milliseconds) : : creates a new date object as zero time plus milliseconds.

Examples: new Date()















code:
                <div class="spec">
                    <a id="datum31"></a><br><br>
                    <a id="datum32"></a><br><br>
                    <a id="datum33"></a><br><br>
                    <a id="datum34"></a><br><br>
                    <a id="datum35"></a><br><br>
                    <a id="datum36"></a><br><br>
                    <a id="datum37"></a><br><br>
                </div>
                <script>
                        var d = new Date();
                        document.getElementById("datum31").innerHTML = "date: " + d;
                        var d = new Date(2018, 11, 24, 10, 33, 30, 0);
                        document.getElementById("datum32").innerHTML = d;
                        var d = new Date(90, 11, 23);
                        document.getElementById("datum33").innerHTML = "date: " + d;
                        var d = new Date("October 13, 2014 11:13:00");
                        document.getElementById("datum34").innerHTML = "date: " +  d;
                        var d = new Date(0);
                        document.getElementById("datum35").innerHTML = "date: " + d;
                        var d = new Date(1500000000000);
                        document.getElementById("datum36").innerHTML = "date: " + d;
                        var d = new Date(1800000000000);
                        document.getElementById("datum37").innerHTML = "date: " + d;
        
                </script>
            

"set" date methods: set part of a date

top

Set Date methods let you set date values (years, months, days, hours, minutes, seconds, milliseconds) for a Date Object.

"set" date methods are:

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

This method can also be used to add days to a date. If adding days shifts the month or year, the changes are handled automatically by the Date object.

setFullYear() : sets the year (optionally month and day).

The setFullYear() method sets the year of a date object. This method can optionally set month and day

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

setMilliseconds() : sets milliseconds (0-999).

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

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

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

setTime() : sets the time (milliseconds since January 1, 1970).

setUTCDate(): sets the day of the month for a specified date according to universal time.

Also available for day, month, fullyear, hours, minutes etc.

Examples












code:
                <div class="spec">
                    <a id="datum38"></a><br>
                    <a id="datum39"></a><br>
                    <a id="datum40"></a><br>
                    <a id="datum41"></a><br>
                    <a id="datum42"></a><br>
                    <a id="datum43"></a><br>
                    <a id="datum44"></a><br>
                    <a id="datum45"></a><br>
                    <a id="datum46"></a><br>
                    <a id="datum47"></a><br>
                    <a id="datum48"></a><br>
                </div>
                <script>
                    var d = new Date();
                    d.setDate(15);
                    document.getElementById("datum38").innerHTML = "date set: " + d;
                    var d = new Date();
                    d.setDate(d.getDate() + 50);
                    document.getElementById("datum39").textContent = "date set: " + d;
                    var d = new Date();
                    d.setFullYear(2020);
                    document.getElementById("datum40").innerHTML = "year set: " + d;
                    var d = new Date();
                    d.setFullYear(2020, 11, 13);
                    document.getElementById("datum41").innerHTML = "year set: " + d;
                    var d = new Date();
                    d.setHours(22);
                    document.getElementById("datum42").innerHTML = "hours set: " +d;
                    var d = new Date();
                    d.setMilliseconds(100);
                    document.getElementById("datum43").innerHTML = "milliseconds set: " + d;
                    var d = new Date();
                    d.setMinutes(30);
                    document.getElementById("datum44").innerHTML = "minutes set: " + d;
                    var d = new Date();
                    d.setMonth(11);
                    document.getElementById("datum45").innerHTML = "month set: " + d;
                    var d = new Date();
                    d.setSeconds(30);
                    document.getElementById("datum46").innerHTML = "seconds set: " + d;
                    var d = new Date();
                    d.setTime(1111111111111)
                    document.getElementById("datum47").innerHTML = "time set: " + d;
                    var d = new Date();
                    d.setUTCDate(23);
                    document.getElementById("datum48").innerHTML = "UTC date set: " +d;
                </script>
            

date methods

top

When a Date object is created, a number of methods allow you to operate on it. Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date objects, using either local time or UTC (universal, or GMT) time.

JavaScript will (by default) output dates in full text string format. When you display a date object in HTML, it is automatically converted to a string, with the toString() method.

toString() methods

toDateString() method : converts a date to a more readable format

toUTCString() method : converts a date to a UTC string (a date display standard).

toISOString() method : converts a date to a string, using the ISO standard format.

Examples







toDateString()



toUTCString()



toISOString()



code:
                <div class="spec">
                    <a id="datum49"></a><br><br>     
                    <a id="datum50"></a><br><br>     
                    <a id="datum51"></a><br><br>     
                    <p>toDateString()</p>
                    <a class="spec" id="datum52"></a><br><br>     
                    <p>toUTCString()</p>
                    <a class="spec" id="datum53"></a><br><br>   
                    <p>toISOString()</p>
                    <a class="spec" id="datum54"></a><br><br>   
                </div>
                <script>
                    var d = new Date();
                    document.getElementById("datum49").innerHTML = "date: " + d;
                    document.getElementById("datum50").innerHTML = "date: " + d.toString();
                    let nu = new Date();
                    document.getElementById('datum51').innerHTML = "current date and time: " + nu;
                    //toDateString()
                    var d = new Date();
                    document.getElementById("datum52").innerHTML = "date: " + d.toDateString();
                    //toUTCString()
                    var d = new Date();
                    document.getElementById("datum53").innerHTML = "date: " + d.toUTCString();
                    //toISOString()
                    var d = new Date();
                    document.getElementById("datum54").innerHTML ="date: " + d.toISOString();
                </script>
            

get the time from a date

By using the .toTimeString() method and slicing the string at the correct place, we can get the time from a date that we provide, or get the current time.

Example - code

        const timeFromDate = date => date.toTimeString().slice(0, 8);
        console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
        // Result: "17:30:00"
    
        const timeFromDate = date => date.toTimeString().slice(0, 8);
        console.log(timeFromDate(new Date()));
        // Result: will log the current time
    
        // get timezone
        const getTimezone = () => Intl.DateTimeFormat().resolvedOptions().
        timeZone;
    

calculate the number of days between two dates

This can be a little tricky to figure out sometimes. The “1000 * 60 * 60 * 24” is the number of milliseconds that are in a single day.

Example - code

        const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
        diffDays(new Date('2014-12-19'), new Date('2020-01-01')); // Result: 1839
    
        const diffDays = (firstDate, secondDate) => Math.round(Math.abs(firstDate - secondDate) / (24 * 60 * 60 * 1000));
        diffDays(firstDate('2014-12-19'), secondDate('2020-01-01')); // Result: 1839
    
        const daysBetween = (one, another) => Math.round(Math.abs((+one) - (+another)) / 8.64e7);
        diffDays(new Date('2014-12-19'), new Date('2020-01-01')); // Result: 1839
    

time zones

top

When setting a date, without specifying the time zone, JavaScript will use the browser's time zone.
When getting a date, without specifying the time zone, the result is converted to the browser's time zone.
In other words: if a date/time is created in GMT (Greenwich Mean Time), the date/time will be converted to CDT (Central US Daylight Time) if a user browses from central US.

getTimezoneOffset() method : returns the time difference between UTC time and local time, in minutes.

Examples: time zones

Click the button to display the time difference between UTC and local time.




code:
                <div class="spec">
                    <p>Click the button to display the time difference between UTC and local time.</p>
                    <button onclick="myFunctionA()">try it</button><br><br>
                    <a id="datum55"></a><br>
                    <a id="datum56"></a>    
                </div>
                <script>
                    function myFunctionA() {
                        var d = new Date();
                        var n = d.getTimezoneOffset();
                        document.getElementById("datum55").innerHTML = "time zone offset in minutes: " + n + " minutes.";
                        document.getElementById("datum56").innerHTML = "time zone offset in hours: " + n/60 + " hours.";
                    }
                </script>
            

time and date examples

top

Display, get, and set examples

examples

Click the button to display the current date and todays day of the month.


code:
                <div class="spec">
                    <button onclick="dayFunction()">Try it</button><br>
                    <a id="day"></a>    
                </div>
                <script>
                    function dayFunction() {
                    var d = new Date();
                    var n = d.getDate();
                    document.getElementById("day").innerHTML = (d + " , - , " + n);
                    }
                </script>
            

P.S. same for minutes, hours, etc.

Today's date and time - version 1.

code:
                <div class="spec">
                    <a id="p1"></a>     
                </div>
                <script>
                    var today = new Date();
                    var date = today.getFullYear() +' - '+ (today.getMonth()+1) + ' - ' + today.getDate();
                    document.getElementById("p1").innerHTML = date;
                </script>
            
code:
                <div class="spec">
                    <a id="p2"></a>         
                </div>
                <script>
                    var today = new Date();
                    var time = today.getHours() + ": " + today.getMinutes() + ": " + today.getSeconds();
                    document.getElementById("p2").innerHTML = time;
                </script>
            

Today's date and time - version 2.

code:
                <div class="spec">
                    <a id="p3"></a>    
                </div>
                <script>
                    var today = new Date();
                    var date = today.getFullYear() + ' - '+ (today.getMonth()+1) + ' - ' + today.getDate();
                    var time = today.getHours() + " : " + today.getMinutes() + " : " + today.getSeconds();
                    var dateTime = date+' '+time;
                    document.getElementById("p3").innerHTML = dateTime;
                </script>
            

Digital clock

code:
                <div class="spec">
                    <a id="digital-clock"></a>      
                </div>
                <script>
                    function getDateTime() {
                            var now     = new Date(); 
                            var year    = now.getFullYear();
                            var month   = now.getMonth()+1; 
                            var day     = now.getDate();
                            var hour    = now.getHours();
                            var minute  = now.getMinutes();
                            var second  = now.getSeconds(); 
                            if(month.toString().length == 1) {
                                month = '0'+ month;
                            }
                            if(day.toString().length == 1) {
                                day = '0'+ day;
                            }   
                            if(hour.toString().length == 1) {
                                hour = '0'+ hour;
                            }
                            if(minute.toString().length == 1) {
                                minute = '0'+ minute;
                            }
                            if(second.toString().length == 1) {
                                second = '0'+ second;
                            }   
                            var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;   
                            return dateTime;
                        }
            
                        // example usage: realtime clock
                        setInterval(function(){
                            currentTime = getDateTime();
                            document.getElementById("digital-clock").innerHTML = currentTime;
                        }, 1000);
                </script>
            

date and time settings




code:
                <div class="spec">
                    <a id="date1a"></a><br>
                    <a id="time1a"></a><br>
                    <a id="timezone1a"></a><br>         
                </div>
                <script>
                    window.onload = setInterval(clock,1000);
                    function clock() {
                        let d = new Date();
                        let date = d.getDate();
                        let month = d.getMonth();
                        let montharr =["Jan","Feb","Mar","April","May","June","July","Aug","Sep","Oct","Nov","Dec"];
                        month=montharr[month];
                        let year = d.getFullYear();
                        let day = d.getDay();
                        let dayarr =["Sunday, ","Monday, ","Tuesday, ","Wednesday, ","Thursday, ","Friday, ","Saturday, "];
                        day=dayarr[day];
                        let hour =d.getHours();
                        let min = d.getMinutes();
                        let sec = d.getSeconds();
                        let msec = d.getMilliseconds();
                        let zone = d.getTimezoneOffset();
                        document.getElementById("date1a").innerHTML=day+" "+date+" "+month+" "+year;
                        document.getElementById("time1a").innerHTML=hour+":"+min+":"+sec+" "+msec;
                        document.getElementById("timezone1a").innerHTML = zone/60;
                    }
                </script> 
            

Current time


code:
                <div class="spec">
                    <a id="time1b"></a><br>         
                </div>
                <script>
                    var today = new Date();
                    var day = today.getDay();
                    var daylist = ["Sunday","Monday","Tuesday","Wednesday ","Thursday","Friday","Saturday"];
                    console.log("Today is : " + daylist[day] + ".");
                    var hour = today.getHours();
                    var minute = today.getMinutes();
                    var second = today.getSeconds();
                    var prepand = (hour >= 12)? " PM ":" AM ";
                    hour = (hour >= 12)? hour - 12: hour;
                    if (hour===0 && prepand===' PM ') 
                    { 
                    if (minute===0 && second===0)
                    { 
                    hour=12;
                    prepand=' Noon';
                    } 
                    else
                    { 
                    hour=12;
                    prepand=' PM';
                    } 
                    } 
                    if (hour===0 && prepand===' AM ') 
                    { 
                    if (minute===0 && second===0)
                    { 
                    hour=12;
                    prepand=' Midnight';
                    } 
                    else
                    { 
                    hour=12;
                    prepand=' AM';
                    } 
                    } 
                    document.getElementById("time1b").innerHTML = "Current Time : "+hour + prepand + " : " + minute + " : " + second;
                </script>
            

current date and time


code:
                    <div class="spec">
                        <a id="id2"></a><br>
                    </div>
                    <script>
                        let now = new Date();
                        document.getElementById("id2").innerHTML = "current date and time: <br>" + now;
                    </script>
                


code:
                    <div class="spec">
                        <a id="id3"></a><br>
                        <a id="id4"></a><br>
                    </div>
                    <script>
                        let date = new Date();
                        document.getElementById("id3").innerHTML = ("current time: " + date.getHours() + " o'clock");
                        document.getElementById("id4").innerHTML = ("current UTC time: " + date.getUTCHours() + " o'clock");
                    </script>
                

code:
                    <div class="spec">
                        <a id="id5"></a><br>
                    </div>
                    <script>
                        document.getElementById("id5").innerHTML = "Time zone offset: " +  ( new Date().getTimezoneOffset()/60 );
                    </script>
                

Github - date examples

examples
date-constructor:
                    const date1 = new Date('December 17, 1995 03:24:00');
                    // Sun Dec 17 1995 03:24:00 GMT...
                    const date2 = new Date('1995-12-17T03:24:00');
                    // Sun Dec 17 1995 03:24:00 GMT...
                    console.log(date1 === date2);
                    // expected output: false;
                    console.log(date1 - date2);
                    // expected output: 0
                
date-getdate:
                    const birthday = new Date('August 19, 1975 23:15:30');
                    const date1 = birthday.getDate();
                    console.log(date1);
                    // expected output: 19
                
date-getday:
                    const birthday = new Date('August 19, 1975 23:15:30');
                    const day1 = birthday.getDay();
                    // Sunday - Saturday : 0 - 6
                    console.log(day1);
                    // expected output: 2
                
date-getfullyear:
                    const moonLanding = new Date('July 20, 69 00:20:18');
                    console.log(moonLanding.getFullYear());
                    // expected output: 1969
                
date-gethours:
                    const birthday = new Date('March 13, 08 04:20');
                    console.log(birthday.getHours());
                    // expected output: 4

                
date-getmilliseconds:
                    const moonLanding = new Date('July 20, 69 00:20:18');
                    moonLanding.setMilliseconds(123);
                    console.log(moonLanding.getMilliseconds());
                    // expected output: 123
                
date-getminutes:
                    const birthday = new Date('March 13, 08 04:20');
                    console.log(birthday.getMinutes());
                    // expected output: 20
                
date-getmonths:
                    const moonLanding = new Date('July 20, 69 00:20:18');
                    console.log(moonLanding.getMonth()); // (January gives 0)
                    // expected output: 6
                
date-getseconds:
                    const moonLanding = new Date('July 20, 69 00:20:18');
                    console.log(moonLanding.getSeconds());
                    // expected output: 18
                
date-gettime:
                    const moonLanding = new Date('July 20, 69 00:20:18 GMT+00:00');
                    // milliseconds since Jan 1, 1970, 00:00:00.000 GMT
                    console.log(moonLanding.getTime());
                    // expected output: -14254782000
                
date-gettimezoneoffset:
                    const date1 = new Date('August 19, 1975 23:15:30 GMT+07:00');
                    const date2 = new Date('August 19, 1975 23:15:30 GMT-02:00');
                    console.log(date1.getTimezoneOffset());
                    // expected output: your local timezone offset in minutes
                    // (eg -120). NOT the timezone offset of the date object.
                    console.log(date1.getTimezoneOffset() === date2.getTimezoneOffset());
                    // expected output: true
                
date-getutcdate:
                    const date1 = new Date('August 19, 1975 23:15:30 GMT+11:00');
                    const date2 = new Date('August 19, 1975 23:15:30 GMT-11:00');
                    console.log(date1.getUTCDate());
                    // expected output: 19
                    console.log(date2.getUTCDate());
                    // expected output: 20
                
date-getutcday:
                    const date1 = new Date('August 19, 1975 23:15:30 GMT+11:00');
                    const date2 = new Date('August 19, 1975 23:15:30 GMT-11:00');
                    // Tuesday
                    console.log(date1.getUTCDay());
                    // expected output: 2
                    // Wednesday
                    console.log(date2.getUTCDay());
                    // expected output: 3
                
date-getutcfullyear:
                    const date1 = new Date('December 31, 1975, 23:15:30 GMT+11:00');
                    const date2 = new Date('December 31, 1975, 23:15:30 GMT-11:00');
                    console.log(date1.getUTCFullYear());
                    // expected output: 1975
                    console.log(date2.getUTCFullYear());
                    // expected output: 1976
                
date-getutchours:
                    const date1 = new Date('December 31, 1975, 23:15:30 GMT+11:00');
                    const date2 = new Date('December 31, 1975, 23:15:30 GMT-11:00');
                    console.log(date1.getUTCHours());
                    // expected output: 12
                    console.log(date2.getUTCHours());
                    // expected output: 10
                
date-getutcmilliseconds:
                    const exampleDate = new Date('2018-01-02T03:04:05.678Z'); // 2 January 2018, 03:04:05.678 (UTC)
                    console.log(exampleDate.getUTCMilliseconds());
                    // expected output: 678
                
date-getutcminutes:
                    const date1 = new Date('1 January 2000 03:15:30 GMT+07:00');
                    const date2 = new Date('1 January 2000 03:15:30 GMT+03:30');
                    console.log(date1.getUTCMinutes()); // 31 Dec 1999 20:15:30 GMT
                    // expected output: 15
                    console.log(date2.getUTCMinutes()); // 31 Dec 1999 23:45:30 GMT
                    // expected output: 45
                
date-getutcmonths:
                    const date1 = new Date('December 31, 1975, 23:15:30 GMT+11:00');
                    const date2 = new Date('December 31, 1975, 23:15:30 GMT-11:00');
                    // December
                    console.log(date1.getUTCMonth());
                    // expected output: 11
                    // January
                    console.log(date2.getUTCMonth());
                    // expected output: 0
                
date-getutcseconds:
                    const moonLanding = new Date('July 20, 1969, 20:18:04 UTC');
                    console.log(moonLanding.getUTCSeconds());
                    // expected output: 4
                
date-now:
                    // this example takes 2 seconds to run
                    const start = Date.now();
                    console.log('starting timer...');
                    // expected output: starting timer...
                    setTimeout(() => {
                    const millis = Date.now() - start;
                    console.log(`seconds elapsed = ${Math.floor(millis / 1000)}`);
                    // expected output : seconds elapsed = 2
                    }, 2000);
                
date-parse:
                    const unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
                    const javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');
                    console.log(unixTimeZero);
                    // expected output: 0
                    console.log(javaScriptRelease);
                    // expected output: 818035920000
                
date-setdate:
                    const event = new Date('August 19, 1975 23:15:30');
                    event.setDate(24);
                    console.log(event.getDate());
                    // expected output: 24
                    event.setDate(32);
                    // Only 31 days in August!
                    console.log(event.getDate());
                    // expected output: 1
                
date-setfullyear:
                    const event = new Date('August 19, 1975 23:15:30');
                    event.setFullYear(1969);
                    console.log(event.getFullYear());
                    // expected output: 1969
                    event.setFullYear(0);
                    console.log(event.getFullYear());
                    // expected output: 0
                
date-sethours:
                    const event = new Date('August 19, 1975 23:15:30');
                    event.setHours(20);
                    console.log(event);
                    // expected output: Tue Aug 19 1975 20:15:30 GMT+0200 (CEST)
                    // (note: your timezone may vary)
                    event.setHours(20, 21, 22);
                    console.log(event);
                    // expected output: Tue Aug 19 1975 20:21:22 GMT+0200 (CEST)

                
date-setmilliseconds:
                    const event = new Date('August 19, 1975 23:15:30');
                    console.log(event.getMilliseconds());
                    // expected output: 0
                    event.setMilliseconds(456);
                    console.log(event.getMilliseconds());
                    // expected output: 456
                
date-setminutes:
                    const event = new Date('August 19, 1975 23:15:30');
                    event.setMinutes(45);
                    console.log(event.getMinutes());
                    // expected output: 45
                    console.log(event);
                    // expected output: Tue Aug 19 1975 23:45:30 GMT+0200 (CEST)
                    // (note: your timezone may vary)
                
date-setmonths:
                    const event = new Date('August 19, 1975 23:15:30');
                    event.setMonth(3);
                    console.log(event.getMonth());
                    // expected output: 3
                    console.log(event);
                    // Sat Apr 19 1975 23:15:30 GMT+0100 (CET)
                    // (note: your timezone may vary)
                
date-setseconds:
                    const event = new Date('August 19, 1975 23:15:30');
                    event.setSeconds(42);
                    console.log(event.getSeconds());
                    // expected output: 42
                    console.log(event);
                    // Sat Apr 19 1975 23:15:42 GMT+0100 (CET)
                    // (note: your timezone may vary)
                
date-settime:
                    const event1 = new Date('July 1, 1999');
                    const event2 = new Date();
                    event2.setTime(event1.getTime());
                    console.log(event1);
                    // expected output: Thu Jul 01 1999 00:00:00 GMT+0200 (CEST)
                    console.log(event2);
                    // expected output: Thu Jul 01 1999 00:00:00 GMT+0200 (CEST)
                    // (note: your timezone may vary)
                
date-setutcdate:
                    const event = new Date('August 19, 1975 23:15:30 GMT-3:00');
                    console.log(event.getUTCDate());
                    // expected output: 20
                    event.setUTCDate(19);
                    console.log(event.getUTCDate());
                    // expected output: 19
                
date-setutcfullyear:
                    const event = new Date('December 31, 1975 23:15:30 GMT-3:00');
                    console.log(event.getUTCFullYear());
                    // expected output: 1976
                    console.log(event.toUTCString());
                    // expected output: Thu, 01 Jan 1976 02:15:30 GMT
                    event.setUTCFullYear(1975);
                    console.log(event.toUTCString());
                    // expected output: Wed, 01 Jan 1975 02:15:30 GMT
                
date-setutchours:
                    const event = new Date('August 19, 1975 23:15:30 GMT-3:00');
                    console.log(event.toUTCString());
                    // expected output: Wed, 20 Aug 1975 02:15:30 GMT
                    console.log(event.getUTCHours());
                    // expected output: 2
                    event.setUTCHours(23);
                    console.log(event.toUTCString());
                    // expected output: Wed, 20 Aug 1975 23:15:30 GMT
                
date-setutcmilliseconds:
                    const date1 = new Date('2018-01-24T12:38:29.069Z');
                    console.log(date1.getUTCMilliseconds());
                    // expected output: 69
                    date1.setUTCMilliseconds(420);
                    console.log(date1.getUTCMilliseconds());
                    // expected output: 420
                
date-setutcminutes:
                    const date1 = new Date('December 31, 1975, 23:15:30 GMT+11:00');
                    console.log(date1.getUTCMinutes());
                    // expected output: 15
                    date1.setUTCMinutes(25);
                    console.log(date1.getUTCMinutes());
                    // expected output: 25
                
date-setutcmonths:
                    const event = new Date('December 31, 1975 23:15:30 GMT-3:00');
                    console.log(event.toUTCString());
                    // Thu, 01 Jan 1976 02:15:30 GMT
                    console.log(event.getUTCMonth());
                    // expected output: 0
                    event.setUTCMonth(11);
                    console.log(event.toUTCString());
                    // expected output: Wed, 01 Dec 1976 02:15:30 GMT
                
date-setutcseconds:
                    const date1 = new Date('December 31, 1975, 23:15:30 GMT+11:00');
                    console.log(date1.getUTCSeconds());
                    // expected output: 30
                    date1.setUTCSeconds(39);
                    console.log(date1.getUTCSeconds());
                    // expected output: 39
            
date-todatestring:
                    const event = new Date(1993, 6, 28, 14, 39, 7);
                    console.log(event.toString());
                    // expected output: Wed Jul 28 1993 14:39:07 GMT+0200 (CEST)
                    // (note: your timezone may vary)
                    console.log(event.toDateString());
                    // expected output: Wed Jul 28 1993
                
date-toisostring:
                    const event = new Date('05 October 2011 14:48 UTC');
                    console.log(event.toString());
                    // expected output: Wed Oct 05 2011 16:48:00 GMT+0200 (CEST)
                    // (note: your timezone may vary)
                    console.log(event.toISOString());
                    // expected output: 2011-10-05T14:48:00.000Z
                
date-tojson:
                    const event = new Date('August 19, 1975 23:15:30 UTC');
                    const jsonDate = event.toJSON();
                    console.log(jsonDate);
                    // expected output: 1975-08-19T23:15:30.000Z
                    console.log(new Date(jsonDate).toUTCString());
                    // expected output: Tue, 19 Aug 1975 23:15:30 GMT

                
date-tolocaledatestring:
                    const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
                    const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
                    console.log(event.toLocaleDateString('de-DE', options));
                    // expected output: Donnerstag, 20. Dezember 2012
                    console.log(event.toLocaleDateString('ar-EG', options));
                    // expected output: الخميس، ٢٠ ديسمبر، ٢٠١٢
                    console.log(event.toLocaleDateString(undefined, options));
                    // expected output: Thursday, December 20, 2012 (varies according to default locale)
                
date-tolocalestring:
                    const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
                    // British English uses day-month-year order and 24-hour time without AM/PM
                    console.log(event.toLocaleString('en-GB', { timeZone: 'UTC' }));
                    // expected output: 20/12/2012, 03:00:00
                    // Korean uses year-month-day order and 12-hour time with AM/PM
                    console.log(event.toLocaleString('ko-KR', { timeZone: 'UTC' }));
                    // expected output: 2012. 12. 20. 오전 3:00:00
                
date-tolocaletimestring:
                    // Depending on timezone, your results will vary
                    const event = new Date('August 19, 1975 23:15:30 GMT+00:00');
                    console.log(event.toLocaleTimeString('en-US'));
                    // expected output: 1:15:30 AM
                    console.log(event.toLocaleTimeString('it-IT'));
                    // expected output: 01:15:30
                    console.log(event.toLocaleTimeString('ar-EG'));
                    // expected output: ١٢:١٥:٣٠ ص
                
date-toprimitive:
                    // Depending on timezone, your results will vary
                    const date = new Date('20 December 2019 14:48');
                    console.log(date[Symbol.toPrimitive]('string'));
                    // expected output: "Fri Dec 20 2019 14:48:00 GMT+0530 (India Standard Time)"
                    console.log(date[Symbol.toPrimitive]('number'));
                    // expected output: 1576833480000
                
date-tostring:
                    const event = new Date('August 19, 1975 23:15:30');
                    console.log(event.toString());
                    // expected output: Tue Aug 19 1975 23:15:30 GMT+0200 (CEST)
                    // (note: your timezone may vary)
                
date-totimestring:
                    const event = new Date('August 19, 1975 23:15:30');
                    console.log(event.toTimeString());
                    // expected output: 23:15:30 GMT+0200 (CEST)
                    // (note: your timezone may vary)
                
date-toutcstring:
                    const event = new Date('14 Jun 2017 00:00:00 PDT');
                    console.log(event.toUTCString());
                    // expected output: Wed, 14 Jun 2017 07:00:00 GMT
                
date-utc:
                    const utcDate1 = new Date(Date.UTC(96, 1, 2, 3, 4, 5));
                    const utcDate2 = new Date(Date.UTC(0, 0, 0, 0, 0, 0));
                    console.log(utcDate1.toUTCString());
                    // expected output: Fri, 02 Feb 1996 03:04:05 GMT
                    console.log(utcDate2.toUTCString());
                    // expected output: Sun, 31 Dec 1899 00:00:00 GMT
                
date-valueof:
                    const date1 = new Date(Date.UTC(96, 1, 2, 3, 4, 5));
                    console.log(date1.valueOf());
                    // expected output: 823230245000
                    const date2 = new Date('02 Feb 1996 03:04:05 GMT');
                    console.log(date2.valueOf());
                    // expected output: 823230245000