This article will show you how to get the current date, time, or both, in the JavaScript programming language. Code examples included.
Date Objects in JavaScript
Date objects represent a single point in time in JavaScript. They are created by initializing a new variable with a new Date object:
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:
console.log(new Date());
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:
"04/05/2022"
Note that the format of the date is locale dependent – The date will be formatted appropriately depending on the locale set on your computer.
Unix Epoch
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();
UTC Time
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.
The JavaScript Date object contains the UTC values for the given date, as well as the current timezone. A string representation of the UTC date/time can be generated using the following:
var now = new Date(); var utc = now.getUTCDate();
Which will assign the value:
"Wed, 04 May 2022 21:55:00 GMT"