Book of Coding


The global objects Date and Math

1. Date and time with JavaScript

JavaScript provides the object Date for working with date and time information. In order to access date and time information, an instance of Date must first be created. Arguments can be passed, but can also be omitted. If the arguments are omitted, an instance is created that represents the current date and time.

  • Access to the individual components of a date/time object
Complete Code - Examples/Part_210/main.js...

 const today = new Date();
 console.log(today.getMonth());      // Returns the current month (0-11)
 console.log(today.getFullYear());   // Returns the year in the format YYYY
 console.log(today.getDate());       // Returns the current day of the month (1-31)
 console.log(today.getDay());        // Returns the day of the week (starts Sunday with 0)                            
 console.log(today.getHours());      // Returns the current hour of the day (0-23)
 console.log(today.getTime());       // Returns the milliseconds since 1 January 1970
                    

The month can be determined via getMonth(), the year via getFullYear(), the current day of the month via getDate(), the current day of the week via getDay(), the current hour via getHours(), etc.


An overview of the most important methods of Date
MethodExplanation
getDate() Returns the day of the month (1-31) for the respective date.
getDay() Returns the day of the week (0-6) for the respective date.
getFullYear() Returns the year for the respective date.
getHours() Returns the hour for the respective date.
getMilliseconds() Returns the milliseconds (0-999) for the respective date.
getMinutes() Returns the minutes (0-59) for the respective date.
getMonth() Returns the month (0-11) for the respective date.
getSeconds() Returns the seconds (0-59) for the respective date.
getTime() Returns the number of milliseconds that have elapsed since 01.01.1970, 00:00:00 UTC for the respective date.
getYear() Returns the year for the respective date, but is obsolete. The method Date.prototype.getFullYear() should be used instead.
setDate(dayValue) Sets the day of the month for the respective date
setFullYear(yearValue [,monthValue [,dayValue]] ) Sets the year for the respective date. Month or day can optionally be specified.
setHours(hoursValue [,minutesValue [,secondsValue [,msValue ]]] ) Sets the hour for the respective date. Minutes, seconds and milliseconds can optionally be specified.
setMilliseconds(millisecondsValue) Sets the milliseconds for the respective date.
setMinutes(minutesValue [,secondsValue [,msValue]]) Sets the minutes for the respective date. Seconds and milliseconds can optionally be specified.
setMonth(monthValue [,dayValue]) Sets the month for the respective date. Optionally, the day can be specified.
setSeconds(secondsValue [,msValue]) Sets the seconds for the respective date. Milliseconds can be specified as an option.
setTime(timeValue) Sets the date and time based on a numerical value that specifies the milliseconds that have elapsed since 01/01/1970, 00:00:00 UTC.
setYear() This method is out of date.

Complete Code - Examples/Part_211/main.js...

 const date1 = new Date();              // current date and time
 const date2 = new Date(1234765000000); // Date based on milliseconds
 // since 01.01.1970

 const date3 = new Date("04 20 2024");  // Date based on string
 const date4 = new Date(                // Date based on ...
   2022,  // ... Year ...
   6,     // ... Month ...
   14,    // ... Day ...
   14,    // ... Hours ...
   23,    // ... Minutes ...
   30,    // ... Seconds ...
   30     // ... and Milliseconds
 );

 console.log(date1); // here: 2024-05-14T14:13:39.074Z
 console.log(date2); // here: 2009-02-16T06:16:40.000Z
 console.log(date3); // here: 2024-04-19T22:00:00.000Z
 console.log(date4); // here: 2022-07-14T12:23:30.030Z

 console.log(date1.getDay());        // here: 2
 console.log(date1.getDate());       // here: 14
 console.log(date1.getMonth());      // here: 4
                        

  • date1: Without an argument, an object is created that represents the current date and time, as from Part_210 today.
  • date2: If a numerical value is passed as an argument, this is evaluated as the number of milliseconds that have elapsed since 1 January 1970, i.e. an object is created that represents the corresponding point in time.
  • date3: A character string can be passed as an argument.
  • date4: The individual dates and times can also be passed individually as numerical values, in this sequence: year, month, day, hour, minute, second, milliseconds.

The next example shows a clock that was created with the object Date and is executed on the browser:

Complete Code - Examples/Part_212/script.js...

 function clock() {
   const today = new Date();
   let h = today.getHours();
   let m = today.getMinutes();
   let s = today.getSeconds();
   m = checkTime(m);
   s = checkTime(s);
   document.getElementById('time').innerHTML =  h + ":" + m + ":" + s;
   // This block of code retrieves the current time, formats it as HH:MM:SS, and updates the content of the 'time' div with the formatted time.
   setTimeout(clock, 1000);
   // This line sets a timer to call the startTime function again after 1000 milliseconds (1 second), allowing the clock to continuously update every second.
 }
                        

The HTML code to execute in the browser:

Complete Code - Examples/Part_212/index.html...

 <body onload="clock()">
     <div id="time"></div>
     <!-- This div will display the current time. Its content will be updated by the JavaScript code. -->
 <script src="script.js"></script>
 </body>
                        


2. Performing complex calculations with Math

Another global object, apart from Date, is Math, for example.Performing simple calculations with numbers in JavaScript is no problem, but if you want to perform complex calculations, it is better to use the Math object.

Examples of simple calculations:


 let x = 21 + 21
 console.log(x);   // output: 42 

 let x = 40 / 4
 console.log(y);   // output: 10
    			    

The Math object provides a whole range of different methods that can be used to perform all kinds of calculations. The next example shows some of the methods that are possible with Math.

Complete Code - Examples/Part_213/main.js...

 console.log(Math.min(0, 420, 47, 2, -7, -42));  // output: -42
 console.log(Math.max(0, 420, 47, 2, -7, -42));  // output: 420
 console.log(Math.random());                     // output of a random number
 console.log(Math.round(5.7));                   // output: 6
 console.log(Math.round(5.4));                   // output: 5
 console.log(Math.ceil(5.4));                    // output: 6
 console.log(Math.floor(5.7));                   // output: 5
					

MethodExplanation
min Output of the minimum of the transferred numerical values
max Output of the maximum of the transferred numerical values
random Output of a random number
round Returns the commercial rounding of a number
ceil Output of the next higher integer greater than or equal to the transferred numerical value
floor Output of the next lowest integer less than or equal to the transferred numerical value

There are many more methods such as Math.cos for cosine calculations or Math.exp for exponential values etc., but the methods shown above are the most commonly used.

The next example shows the Math object as it can be used in the browser:

Complete Code - Examples/Part_214/script.js...

 /* generates a random number from 0-10 */
 function random1() {
     var rnd1 = Math.floor(Math.random() * 10);
     document.getElementById('rndNr1').value = rnd1;
 }

 /* generates a random number from 0-1000000 */
 function random2() {
     var rnd2 = Math.floor(Math.random() * 1000000);
     document.getElementById('rndNr2').value = rnd2;
 }
					

The HTML code to execute in the browser:

Complete Code - Examples/Part_214/index.html...

 <body>
     <p>Generates a random number from 0-10</p>
     <input type="text" id="rndNr1" name="input" />
     <input type="button" value="Random Number 0-10" onclick="random1();" />
     <p>Generates a random number from 0-1000000</p>
     <input type="text" id="rndNr2" name="input" />
     <input type="button" value="Random Number 0-1000000" onclick="random2();" />
 <script src="script.js"></script>
 </body>
					


Related links: