Knowing how to handle date and time is crucial both for offering website users high-quality user experience and handling server-side operations. To help page visitors search for the latest blog entries, comments or messages, validate inputs and organize content, a developer needs to be skilled at manipulating date and time JavaScript objects.
Being able to set and optimize dates to the user’s time zone is even more important when developing appointment-scheduling tools, tracking arrivals and departures, or monitoring events in real-time.
This post will give a walk-through date and time objects and all the ways to format them.
Taking Time Zones Into Account
Although there are dozens of time zones, in JavaScript, there are only two relevant ways to refer to a time zone:
- UTC – a marker for specifying the time zone, similar to the GMT abbreviation;
- Local – sets the time zone by defining the location of the computer.
Adapting to IP-based local date in time is a way most scripts operate by default. In case you specify a UTC, all the website visitors will see the same time data, without taking location into account.
Default Date Object
Getting Current Date
The date is a built-in parameter that will display your device’s local data. To see the current date, create a variable with the date function:
const today = new Date();
The output of the system will be your device’s current local date and time, as shown in the example below:
Mon Jan 20 2020 08:15:15: GMT +1000 (EST)
To display the date in a year-month-day-format, add the following code to the variable:
const today = new Date();
const date = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`
You can use these methods separately to get a year, a month, or a day from the system.
If a document contains multiple dates, be sure to specify the one you are referring to when using getFullYear() or getMonth(), as shown in the example below:
const date2 = new Date("January 20, 2020");
const month = date2.getMonth() + 1
Note: Although JavaScript translates dates to the human language, the information used to calculate dates is the timestamp – the number of milliseconds counted since January 1st 1970.
Getting current time
A developer can get the timestamp data as well by using newDate.getTime() or Date.now(). To get a current timestamp, enter nowGetTime().
Another way to display the current time is by setting the time variable and specifying the time format. The code will look the following way:
const today = new Date();
const time = `${today.getHours()}:${today.getMinutes()}:${today.getSeconds()}.
Now that you know how to set a date in JavaScript, let’s take a look at different ways to format dates in JS.
Four Ways to Create Dates
Whenever you read a forum thread or a post on JavaScript, you might spot words like ‘date-string’, arguments, no arguments. These refer to four basic ways to declare dates in JS.
Strings
The method refers to creating dates by passing a string of numbers to new Date – new Date”2020-01-20”. Keep in mind that a yy-mm-dd format is used instead of a dd-mm-yy one – otherwise, you will get an ‘invalid data’ error.
Date-strings are not preferred among developers due to their GMT reliance. In case you live behind GMT – the date will be Jan, 20. If you are ahead of the time zone, it becomes Jan, 21. To see the error for yourself, set a date and enter cosole.log() to see the full view.
Arguments
Setting dates using arguments allows developers to enter up to 7 variables so that date variables are highly precise:
- Year – 4 digits;
- Month – numbers from 1 to 11
- Day – from 1 to 31
- Hour – the range of numbers from 0 to 23
- Minutes – from 0 to 59;
- Seconds – from 0 to 59;
- Milliseconds – the range is 0-999.
If you set dates by arguments, new Date will have the following look:
new Date (2020, 0, 20, 8, 15, 15, 15)
Note: pay attention that January is a zero-indexed value, not 1.
Time Stamps
We already described how to see a real-time timestamp. To set a custom one, enter the desired amount of milliseconds in parentheses of new Date()
new Date(1560211225000)
With no argument
You can set the current date as the new date. In that case, leave the space in the parentheses empty:
new Date()
All Useful Commands For Managing Date and Time
Retrieving dates using getDate()
Command | Description | Example of the output |
getFullYear() | Retrieves the current year | 2020 |
getMonth() | Retrieves the current month (months are named by numerical values from 0 to 11) | 0 |
getDate() | Shows the current day of a month | 20 |
getDay() | Shows the day of the week | 1 (range is 0-6, 0 is Sunday) |
getHours() | Retrieves the current hour | 8 (0-23, where 0 stands for midnight) |
getMinutes() | Shows the current number of minutes | 15 |
getSeconds() | Shows the current seconds | 15 |
getMlliseconds() | Shows the number of milliseconds | 15 |
Retrieving UTC dates
Command | Description | Example |
getUTCFullYear() | Shows the current year in the UTC format | 2020 |
getUTCMonth() | Shows the current month in the UTC format | 0 |
getUTCDate() | Shows the current date in the UTC format | 20 |
getUTCDay() | Shows the day of the week | 1 |
getUTCHours() | Shows the hours in the UTC format | 8 |
getUTCMinutes() | Shows the number of minutes in the UTC format | 8 |
getUTCSeconds() | Shows the number of seconds in the UTC format | 15 |
getUTCMilliseconds() | Shows the number of milliseconds in the UTC format | 15 |
Using setDate() to declare new dates
Command | Description | Example |
setFullYear() | Sets a specified year | 2020 |
setMonth() | Sets a month | 0 |
setDate() | Sets a day of a month | 20 |
setDay() | Sets a day of the week | 1 |
setHours() | Sets the hour | 8 |
setMinutes() | Sets the number of minutes | 15 |
setSeconds() | Sets the number of seconds | 15 |
setMilliseconds() | Sets the number of milliseconds | 15 |
setTime() | Sets timestamps | 1579404751 |
Creating dates using new Date()
Command | Description |
new Date() | Sets the current date as a new one |
new Date([string]) | Declares a date in the string format |
new Date (YYYY-MM-DD-hh-mm-ss-mmms) | Declares a date as an argument |
new Date(timestamp) | Declares a chosen timestamp as a date. |
Conclusion
Setting dates via JS is challenging because there isn’t a universal way to do it. The good news is, there are multiple libraries that simplify the process of data formatting and manipulating. Having said that, mastering the basics of date and time manipulation is a useful skill that will come in handy multiple times in the development process.
If you are still confused about the Date object, consider going through documentation or reference guides on Mozilla Developer Network. Hopefully, you will master the concept in no time.
Great content! Super high-quality! Keep it up! 🙂