JavaScript Utilities: Math, Date
September 26, 2018
In this tutorial we will learn about two built-in utilities of JavaScript — the Math
module and the Date
module.
Math
The Math
module has functions to do various mathematical operations, and it also includes functions for generating random numbers. It has many constant values as well, like the value of pi
(ratio of a circle’s circumference to its diameter), etc.
Math Constants
Let’s start by looking at some of the constants defined in the Math
object. We will use the JavaScript Console for this tutorial to run the examples interactively.
Math.E
is the Euler’s constant — $e$. It is used as the base of natural logarithm, and its value is approximately 2.718
.
> Math.E
< 2.718281828459045
Math.PI
is the ratio of a circle’s circumference to its diameter. It’s value is approximately equal to 3.14
.
> Math.PI
< 3.141592653589793
Similarly, there are some other constants available:
- Square root of 1/2, or $\sqrt{1/2}$ .
> Math.SQRT1_2
< 0.7071067811865476
- Square root of 2, or $\sqrt{2}$.
> Math.SQRT2
< 1.4142135623730951
- Logarithm of
Math.E
to the base 2, or $\log_2e$.
> Math.LOG2E
< 1.4426950408889634
- Logarithm of
Math.E
to the base 10, or $\log_{10}{e}$.
> Math.LOG10E
< 0.4342944819032518
Math Methods
Let’s look at some of the methods defined in the Math
object.
Basic math functions and rounding:
Math.abs(x)
gives the absolute value of x i.e. if x >= 0
it returns x
, if x < 0
then it returns -x
. Basically, it returns the value of x without its sign.
> Math.abs(-6.2)
< 6.2
> Math.abs(4.8)
< 4.8
Math.pow(x, y)
: $x$ raised to the power $y$, or $x^y$.
> Math.pow(2, 5)
< 32
> Math.pow(3, 2)
< 9
Math.exp(x)
:Math.E
raised to the power $x$, or $e^x$.
> Math.exp(1) // Equal to Math.E
< 2.718281828459045
Math.floor(x)
: Greatest integer smaller thanx
.
> Math.floor(4.5)
< 4
> Math.floor(3.4)
< 3
> Math.floor(-4.5) // slightly counter-intuitive for negative numbers
< -5
Math.ceil(x)
: Smallest integer greater thanx
.
> Math.ceil(4.5)
< 5
> Math.ceil(3.4)
< 4
Math.round(x)
:x
rounded to the nearest integer.
> Math.round(4.5)
< 5
> Math.round(3.4)
< 3
Math.sqrt(x)
: Square root ofx
.
> Math.sqrt(2)
< 1.4142135623730951
> Math.sqrt(100)
< 10
Minimum and maximum:
Math.max(...)
and Math.min(...)
give maximum and minimum respectively.
> Math.max(1, 334, 53, 2)
< 334
> Math.min(1, 334, 53, 2)
< 1
Logarithm functions:
Math.log(x)
: Natural logarithm of $x$, or $\ln x$.
> Math.log(Math.E)
< 1
Math.log10(x)
: Logarithm of $x$ to the base 10, or $\log_{10}x$.
> Math.log10(10)
< 1
> Math.log10(100)
< 2
> Math.log10(1000)
< 3
> Math.log10(300)
< 2.4771212547196626
Math.log2(x)
: Logarithm of $x$ to the base 2, or $\log_{2}x$.
> Math.log2(4)
< 2
> Math.log2(32)
< 5
> Math.log2(6)
< 2.584962500721156
Trigonometric functions:
Math.sin(x)
: Sine of $x$. The value of $x$ is expected to be in radians.
> Math.sin(Math.PI / 2)
< 1
> Math.sin(Math.PI)
< 0
Math.cos(x)
: Cosine of $x$. The value of $x$ is taken in radians.
> Math.cos(0)
< 1
> Math.cos(Math.PI)
< -1
Math.tan(x)
: Tangent of $x$. The value of $x$ is taken in radians.
> Math.tan(0)
< 0
> Math.tan(Math.PI / 3) // Math.sqrt(3)
< 1.7320508075688767
Similarly, there are other trigonometric functions as well, like Math.acos(x)
, Math.asin(x)
and Math.atan(x)
.
Generating random numbers
Many applications require random numbers. For example, let’s say you are making a card game, then you will require random numbers to shuffle a deck of cards.
The Math
object has a method random()
for which generates random numbers between 0 and 1.
Using this function we can generate random numbers between any two numbers as well. Here’s how:
=> Math.random() ranges from 0 to 1
=> Math.random() * N ranges from 0 to N
=> X + Math.random() * N ranges from X to X + N
To get random numbers between two numbers X and Y we can use the following
var delta = Y - X;
var randomNumber = X + Math.random() * delta;
To generate random integers, use Math.floor()
with Math.random()
. For example:
// random integer from 0 to 9 (both inclusive)
Math.floor(Math.random() * 10);
// random integer from 1 to 100 (both inclusive)
1 + Math.floor(Math.random() * 100);
In particular, the above is useful for selecting random elements from an array:
function randomElement(arr) {
// indices are from 0 to arr.length - 1
var randomIndex = Math.floor( Math.random() * arr.length );
return arr[randomIndex];
}
Date
The Date
module is used to represent time. It has date-time objects which store all the information about current time, date, month, year, etc and it also allows us to do various operations using date-times.
Dates are stored as timestamps, which is defined as the number of milliseconds that have passed since January 1, 1970 UTC
. This date is called epoch or in simple words JavaScript considers this date as the beginning of time.
The syntax for creating a new Date object:
var date = new Date();
This creates a new Date
object which stores current date. A string can be passed to Date()
to create a date object which stores the desired date. For example,
var date1 = new Date("3-3-2018");
var date2 = new Date("3 march 2018");
var date3 = new Date("march 3 2018");
var date4 = new Date("2018 march 3 3:45 pm");
All of these are valid dates. The YYYY-MM-DD
format is the preferred JavaScript date format. You can also omit some parts like the date, or the time. In the date string, time can be given in both 12 hour or 24 hour format.
You can also pass a number to new Date()
. For example,
var date5 = new Date(1024);
The number is the number of milliseconds since Jan 1 1970 UTC.
Getters and setters
There are many get and set functions which can be used to get/set date information from/in a Date object. These methods are getDate
, setDate
, getMonth
, setMonth
, getFullYear
, setYear
, getHours
, setHours
, getMinutes
, setMinutes
, getSeconds
, setSeconds
, getMilliseconds
and setMilliseconds
.
Let’s see how to use the get functions. Create a new HTML file:
<html>
<head>
<title>JavaScript: Date</title>
<script>
function printDateValues() {
}
</script>
</head>
<body>
Date: <input type="date" id="dateinput"> <br>
Time: <input type="time" id="timeinput"> <br>
<button onclick="printDateValues()">
Print Date Values
</button> <br>
<p id="results">
Date values will be printed here.
</p>
</body>
</html>
We have used two new types of input elements which are date and time. The date <input>
element displays a calendar and can be used to give any date.
The time <input>
element has two values, hour and minutes. It uses the 24 hour format.
The function printDateValues()
will take the values date <input>
and time <input>
and create a new Date()
from it. Then we will print all the values using the get
functions listed above. Write the function like this:
function printDateValues() {
var dateinput = document.getElementById("dateinput");
var timeinput = document.getElementById("timeinput");
var ptag = document.getElementById("results");
var date = new Date(dateinput.value + " " + timeinput.value);
var results = date + "<br>";
results += "Day: " + date.getDay() + "<br>";
results += "Date: " + date.getDate() + "<br>";
results += "Month: " + date.getMonth() + "<br>";
results += "Year: " + date.getFullYear() + "<br>";
results += "Hours: " + date.getHours() + "<br>";
results += "Minutes: " + date.getMinutes() + "<br>";
results += "Seconds: " + date.getSeconds() + "<br>";
results += "Milliseconds: " + date.getMilliseconds() + "<br>";
ptag.innerHTML = results;
}
Select date and time values and then click the button. You should see all the values printed inside the <p>
tag.
getMonth()
and getDay()
returns the index of the month and day in the Date object. Months start from 0 (January) and go till 11 (December). Days start from 0 (Sunday) and go till 6 (Saturday).
We can also create another function to see an example of how set functions work.
function setDateExample() {
var ptag = document.getElementById("results");
var date = new Date("March 3 2018");
var results = "";
results += "Date value = " + date + "<br>";
date.setDate(19);
date.setFullYear(2020);
date.setMonth(4);
results += "Date has been modified <br>";
results += "Date now = " + date + "<br>";
ptag.innerText = results;
}
and add another button in the HTML
<button onclick="setDateExample()">Run set date example</button> <br>
When you click this button you should see the following output
Date value = Sat Mar 03 2018 00:00:00 GMT+0530 (India Standard Time)
Date has been modified
Date now = Tue May 19 2020 00:00:00 GMT+0530 (India Standard Time)
Converting Timezones
For timezone conversions there isn’t any pre-defined function. So, we’ll have to make our own. By default, JavaScript returns the local time zone. For example, I am in India, so when I write:
> new Date();
on the console, I get:
< Sat Sep 15 2018 06:48:48 GMT+0530 (India Standard Time)
Today’s date in Indian Standard Time.
IST
is GMT+0530
which means Indian Standard Time is 5 hours and 30 minutes ahead of Greenwich Mean Time. We wish to convert this time to another time zone, say, GMT-0230
. We’ll do it the following way:
- Convert local time to GMT time
- Convert GMT time to desired timezone,
GMT-0230
in this example.
Convert local time to GMT
var d = new Date();
d
stores current date in local time. We can get the local timezone offset by using the getTimezoneOffset()
method. It returns the number of minutes the local time zone is ahead/behind the GMT time. If local time is ahead, it returns a negative value. If local time is behind, it returns a positive value.
If we add the offset value in d.getMinutes()
, we should get the GMT time.
d.setMinutes(d.getMinutes() + d.getTimezoneOffset());
This changes the date to GMT timezone.
Convert GMT time to desired timezone
The desired timezone is GMT-0230
, which means 2 hours and 30 minutes behind GMT or 2 * 60 + 30 = 150
minutes behind GMT. We can again do the same thing by setting the minutes value:
d.setMinutes(d.getMinutes() + 150);
This will change the time to GMT-0230
.
Putting it all together
Let’s create a function which takes a date object and the desired time zone as parameters and changes the date in the date object to the desired time zone.
function changeTimezone(date, tz) {
// tz is of the format +hhmm or -hhmm
var sign = tz[0];
var hours = tz[1] + tz[2];
hours = parseInt(hours);
var minutes = tz[3] + tz[4];
minutes = parseInt(minutes);
// convert local to GMT
date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
// convert GMT to tz
// convert hours and minutes to minutes
var difference = hours * 60 + minutes;
// if sign is - then we need to subtract minutes
if (sign == '-')
difference = difference * -1;
date.setMinutes(date.getMinutes() + difference);
}
The timezone string passed should be of the format -hhmm
or +hhmm
. We have broken the timezone string into sign, hours and minutes. Rest of the code is following the logic explained above.
Calculating elapsed time
We can use a Date object to calculate time taken by JavaScript to complete a particular task. For example, let us calculate how long does it take JavaScript to run a for loop which goes from 1 to 1000000. We will print the results on the console using console.log()
.
<button onclick=calculateElapsedTime()>Click Me!</button>
<script>
function calculateElapsedTime() {
var start = Date.now();
var count = 0;
for (var i = 1; i <= 1000000; i++) {
count++;
}
var end = Date.now();
console.log("Time taken: ", end - start, " milliseconds");
}
</script>
We have used the Date.now()
method which returns the number of milliseconds passed since January 1 1970 UTC. We store the time before starting the loop and after the loop has ended we print the difference of the two values.
This prints:
Time take: 4 milliseconds
on my machine (ranges from 3 - 5 milliseconds on different runs). The execution time might be different on your machine.
Conclusion
We learnt about two very important modules of JavaScript. The methods in these modules will be helpful when you implement your projects.