Let's meet a new integrated object: new Date(). It saves the date, time and gives data/time management options.
We may, for instance, utilize it for saving creation / change timings, measuring time or just printing the actual date.
Call new Date()
with one of the following parameters to generate a new Date()
object:
- new Date()
- new Date(milliseconds)
- new Date("datestring")
- new Date(year, month, date, hours, minutes, seconds, ms)
new Date()
Creating an object for the current Date
and time without any argument:
let now = new Date();
console.log( now ); // shows current date/time
new Date(milliseconds)
Create a Date
object with the time equivalent to the milliseconds after 1 Jan 1970 UTC+0. (1s / 1000ms)
// 0 means 01.01.1970 UTC+0
let Jan01_1970 = new Date(0);
console.log( Jan01_1970 );
A time stamp is termed an integer count which represents the amount of milliseconds that transpired since early 1970.
This is a numerically lightweight representation of a Date
.
With a timestamp, we can always generate a date
using a new Date()
and convert the old database object to a timestamp.
The method .getTime()
(see below).
// now add 24 hours, get 02.01.1970 UTC+0
let Jan02_1970 = new Date(24 * 3600 * 1000);
console.log( Jan02_1970 );
There are negative timestamps before 1 January 1970, e.g.:
// 31 Dec 1969
let Dec31_1969 = new Date(-24 * 3600 * 1000);
alert( Dec31_1969 );
new Date("datestring")
If a single parameter is present and it is a string, it will be automatically scanned.
We're going to cover the algorithm like Date.parse
does later.
let date = new Date("2017-01-26");
console.log( date );
The time is not provided and is presumed to be GMT by midnight and adjusted to the time zone in which the code will work, thus the outcome may be
Thu Jan 26 2017 11:00:00 GMT+1100 (Australian Eastern Daylight Time)
orWed Jan 25 2017 16:00:00 GMT-0800 (Pacific Standard Time)
new Date(year, month, date, hours, minutes, seconds, ms)
In the local time zone, create the date with the components. Only the first two are require.
- The
year
needs four numbers:2013
is all right,98
isn't. - The number of
month
begins with0
(Jan), to11
(Dec). - If the
date
argument was not present, the date argument is1
. - If
hours/minutes/seconds/ms
are missing,0
is assumed.
For instance:
new Date(2011, 0, 1, 0, 0, 0, 0); // 1 Jan 2011, 00:00:00
new Date(2011, 0, 1); // the same, hours etc are 0 by default
The maximal precision is 1 ms (1/1000 sec):
let date = new Date(2011, 0, 1, 2, 3, 4, 567);
console.log( date ); // 1.01.2011, 02:03:04.567
Thanks for reading the article โค๏ธ