Math object and Date object
Math object
The built-in Math
object has properties for mathematical constants and methods for mathematical functions.
Math
works with regular JavaScript floating point numbers.
It does not work with BigInt
.
Unlike many other global objects, Math
is not a constructor.
All properties and methods of Math
are static, so
you cannot create a Math
object by using the new
keyword.
Mathematical constants are simply referred to as Math
properties and mathematical functions are simply called as Math
methods.
console.log(Math.PI); // logs: 3.141592653589793
console.log(Math.sin(Math.PI)); // logs: 1.2246467991473532e-16;
In the example above we can see that trigonometric methods take arguments in radians.
We can also see that the methods do not use strict mathematical manipulations
that would have resulted in precise calculations such as
electronic calculators typically provide.
Math
methods use numerical methods
on floating points, resulting in approximations. The sine of Pi radians is precisely zero, approximated by
1.2246467991473532e−16 in the example above.
Constants and results are presented with the full precision of floating points in JavaScript, i.e.,
presented as decimal numbers, rounded to 16 to 17 significant decimal digits. Also keep in mind that different browsers may give slightly different result.
This is a
list of all Math
properties and methods.
Date object
let today = new Date();
let endYear = new Date(today.getFullYear(), 11, 31, 23, 59, 59, 999);
let msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day
let daysLeft = (endYear.getTime() - today.getTime()) / msPerDay;
daysLeft = Math.floor(daysLeft); // full days left in the year
document.querySelector('#display_days_left').textContent =
`${today.getFullYear()} has ${daysLeft} full days left.`;
Result:
Date()
object in JavaScript
JavaScript does not provide a date data type. The Date
object and its methods are used to implement dates and times
in JavaScript, as for the example in figure 1.
When Date()
is called as a function, it returns a string representing the current date and time. It is the local time,
provided by the user's device.
console.log(Date()); // logged: "Fri Feb 04 2022 18:13:05 GMT+0100 (Central European Standard Time)"
console.log(Date.now()); // logged: 1643994785632 // milliseconds since Unix epoch.
Internally the Date
object stores a single moment in time as an integer (floating point number)
representing the number of milliseconds that have elapsed since midnight (00:00:00) on January 1, 1970, UTC,
the so called Unix Timestamp in milliseconds.
This timestamp can be obtained by calling method Date.now()
, as shown in the example above.
The Unix epoch (00:00:00 on 1 January 1970 UTC) is an arbitrary moment defined in timezone UTC±00:00. UTC refers to the global time standard Coordinated Universal Time (UTC). UTC±00:00, usually denoted as just "UTC" (although technically not the same), specifies the timezone in areas roughly around the Greenwich meridian passing through London, England. UTC (UTC±00:00) is also referred to as the Greenwich Mean Time (GMT) or denoted by the letter Z for "zero hours" or "Zulu time" (NATO phonetic alphabet word for Z is "Zulu").
The maximum/minimum representable dates are not of the same values as Number.MAX_SAFE_INTEGER
/Number.MIN_SAFE_INTEGER
(±9 007 199 254 740 991). The Date
object range is ±100 000 000 days relative to 01 January, 1970 UTC (±8 640 000 000 000 000 milliseconds).
This means Date
can represent dates from April 20, 271821 BCE
to September 13, 275760 CE.
In the example above the logged timestamp in milliseconds does not necessarily correspond to the date and time logged by the statement before that.
This is because both statements execute successively and not at the exact same time. This can be circumvented by creating a new Date
object
by calling Date
as a constructor. A date/time is captured at the moment the new Date
object is created. This object
inherited methods from the constructor that can be used to convert this time to various formats.
let now = new Date();
console.log(now.toString()); // logged: "Fri Feb 04 2022 18:13:05 GMT+0100 (Central European Standard Time)"
console.log(now.getTime()); // logged: 1643994785000 // milliseconds since Unix epoch.
console.log(Number(now)); // logged: 1643994785000 // milliseconds since Unix epoch.
As mentioned before, internally the time is stored as a timestamp (which is equal in any timezone) calculated from the Unix epoch, which is in UTC. The captured time is generally in the local time provided by the user's device and needs to be converted to UTC first, before the timestamp can be calculated.
The Date
object provides several methods to return the timestamp as a date or time in various formats, in UTC or local timezone.
In general, methods take or return the time according to the device's local time settings. The .toString()
method in the example above,
for instance, returned the time in UTC+01:00, because this was the device's timezone setting.
There are also methods available that take or return the time in UTC. They typically have "UTC" in their name.
let now = new Date();
console.log(now.toString()); // logged: "Fri Feb 04 2022 18:13:05 GMT+0100 (Central European Standard Time)"
console.log(now.toUTCString()); // logged: "Fri, 04 Feb 2022 17:13:05 GMT"
console.log(now.getHours()); // logged: 18
console.log(now.getUTCHours()); // logged: 17
Without an argument, the new Date
object captures the current time (example above). The argument can also be a specified date/time, creating
a timestamp of milliseconds between the Unix epoch and the specified moment.
let Xmas95 = new Date("1995-12-25T13:30:00");
console.log(Xmas95.toString()); // logs: "Mon Dec 25 1995 13:30:00 GMT+0100 (Central European Standard Time)"
Also in this case, the specified time by the argument is generally conceived as the local time, and is internally converted to UTC first, to be able to calculate the timestamp. However, it is also possible to provide a time specifically in UTC. In the example below, a "Z" (zero hours) is added at the end of the time string, indicating time in UTC.
let birthday = new Date("1990-12-06T04:34:00");
console.log(birthday.toUTCString()); // logs: "Thu, 06 Dec 1990 03:34:00 GMT"
console.log(birthday.getTime()); // logs: 660454440000
let birthdayUTC = new Date("1990-12-06T03:34:00Z"); // The "Z" (zero hours) at the end of the string indicates timezone UTC±00:00.
console.log(birthdayUTC.toString()); // logs: "Thu Dec 06 1990 04:34:00 GMT+0100 (Central European Standard Time)"
console.log(birthdayUTC.getTime()); // logs: 660454440000
BTW: Note that in the above example the arguments of the two new Date()
differ by one hour.
In the above examples the date/time is provided as a string in a ISO 8601 format.
Other date/time formats in strings are possible
(e.g "December 25, 1995 13:30:00"
) but interpretation by browsers is inconsistent. The time can also be provided
as a comma separated sequence of integers. It is also possible to provide the time as a timestamp in milliseconds.
// All assign the same time to "birthday":
let birthday;
birthday = new Date("1990-12-06T04:34:00"); // Local time (UTC+01:00)
birthday = new Date(1990,11,6,4,34,0); // Local time (UTC+01:00), the month is 0-indexed!
birthday = new Date(660454440000);
// the time provided in UTC:
birthday = new Date("1990-12-06T03:34:00Z");
birthday = new Date(Date.UTC(1990,11,6,3,34,0));
In the example above the method
Date.UTC()
is used to provide a date as a sequence of numbers, but then interpreted as a UTC time.
The month is 0-indexed (later more about this).
We have seen some "get" methods (e.g. .getHours()
) and some "to" methods (e.g. .toUTCString()
),
but there are also "set" methods, to (re)set some part(s) of the time hold by a Date
object.
let now = new Date();
let birthday = new Date("1990-12-06T04:34:00");
birthday.setFullYear(now.getFullYear()); // Set year to current year (was 2022 at the time of writing)
console.log(birthday.toString()); // logged: "Tue Dec 06 2022 04:34:00 GMT+0100 (Central European Standard Time)"
These methods use integers to set/get values as follows:
- Milliseconds: 0 to 999
- Seconds and minutes: 0 to 59
- Hours: 0 to 23
- Day: 0 (Sunday) to 6 (Saturday) — 0-indexed
- Date: 1 to 31 (day of the month)
- Months: 0 (January) to 11 (December) — 0-indexed
- Year: inconsistent interpretation (see next)
A two-digit year (e.g. 22) is in some cases interpreted as the actual year 22 CE, in some cases as an offset from the year 1900 (1922), and in other cases as an offset from the year 2000 (2022).
let date;
date = new Date("02/01/22"); // Tue, 01 Feb 2022 00:00:00 GMT // 2022
date = new Date("0022-02-01T00:00:00Z"); // Tue, 01 Feb 0022 00:00:00 GMT // 0022
date = new Date("22-02-01T00:00:00Z"); // Invalid Date
date = new Date(0022,1,1,1,0,0); // Fri, 01 Feb 1918 00:00:00 GMT
// In strict mode: SyntaxError: "0"-prefixed octal literals are deprecated; use the "0o" prefix instead
date = new Date(22,1,1,1,0,0); // Wed, 01 Feb 1922 00:00:00 GMT
date = new Date(2022,1,1,1,0,0); // Tue, 01 Feb 2022 00:00:00 GMT
date.setYear(22); // Wed, 01 Feb 1922 00:00:00 GMT
date.setFullYear(22); // Tue, 01 Feb 0022 00:00:00 GMT
date.setFullYear(0022); // Thu, 01 Feb 0018 00:42:30 GMT
// In strict mode: SyntaxError: "0"-prefixed octal literals are deprecated; use the "0o" prefix
Set the actual year 22 in the first century CE:
let date = new Date("0022-02-01T00:00:00Z");
console.log(date.toUTCString()); // logs: "Tue, 01 Feb 0022 00:00:00 GMT"
let date = new Date(22,1,1,1,0,0);
date.setFullYear(22);
console.log(date.toUTCString()); // logs: "Tue, 01 Feb 0022 00:00:00 GMT"
Also the "set" and "get" methods are timezone sensitive: generally the time is interpreted as local time, unless the "UTC-named" alternative of the method is used.
let someTime = new Date(Date.UTC(2000,0,1,0,0,0));
console.log(someTime.toUTCString()); logs: "Sat, 01 Jan 2000 00:00:00 GMT"
someTime.setHours(1); // Hours set to 1 in local GMT+01:00, which means 0 in GMT. Nothing changed.
console.log(someTime.toUTCString()); logs: "Sat, 01 Jan 2000 00:00:00 GMT"
someTime.setUTCHours(1); // Hours set to 1 in GMT.
console.log(someTime.toUTCString()); logs: "Sat, 01 Jan 2000 01:00:00 GMT"
Calculating elapsed time:
let start = new Date()
// The event to time goes here:
for (let i=0,a; i<10000000; i++) { a=i; }
let end = new Date()
let elapsed = end.getTime() - start.getTime() // elapsed time in milliseconds
console.log(elapsed); // logged: 57 // on my old computer