var now = new Date();
By default, new Date objects are initialized to contain the date and time at the instant they were created, along with timezone details for the current device – thus representing the current date and time:
The above will print the stringified version of the Date object, displaying the information contained within:
Date Wed May 04 2022 22:44:06 GMT+0100 (British Summer Time)
Date object can also be used to manipulate and compare dates.
Get the Current Time as a String
Once a Date object has been created, the detauls for the current date/time can be extracted from it:
var now = new Date(); var currentTime = now.toTimeString();
This will return the current time as a string:
"22:47:30 GMT+0100 (British Summer Time)"
Get the Current Date as a String
Similarly, the date can also be retrieved separately:
var now = new Date(); var currentDate = now.toLocaleDateString();
Which assigns the date value:
Note that the format of the date is locale dependent – The date will be formatted appropriately depending on the locale set on your computer.
Time is often measured in programming as the number of milliseconds since January 1, 1970, 00:00:00 UTC – known as the Unix Epoch Time or Unix Time.
The getTime() method will return this value – an integer count of the number of seconds since January 1, 1970:
var now = new Date(); var unixTime = now.getTime();
If you are building applications for the web, you should consider that your users will all be in different timezones. It’s best to work with UTC time wherever possible, and convert to the users local time when displaying the time, so that everything is consistent when values are stored.
var now = new Date(); var utc = now.getUTCDate();
Which will assign the value:
"Wed, 04 May 2022 21:55:00 GMT"