Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
In our previous blog on date and time in JavaScript, we discussed date creation methods and retrieving them using the get methods. If you have not read our previous article, it is highly recommended to read it first for a crystal clear understanding of the concept.
In this article, we are going to learn the date and time methods in JavaScript. So, without any further ado, let's get started!
There is a set method for each of the get methods we learned about in the previous blog.
Set is used to modify components of a date, whereas get is used to retrieve a specific component from a date. The set methods of the Date object are detailed in the table below.
Date
Method
Range
Year
setFullYear()
YYYY
Month
setMonth()
0-11
Day(month)
setDate()
1-31
Day(week)
setDay()
0-6
Hour
setHours()
0-23
Minute
setMinutes()
0-59
Second
setSeconds()
0-59
Millisecond
setMilliseconds()
0-999
Timestamp
setTime()
In milliseconds since the epoch time.
These set methods can be used to change one, more, or all of the components of a date. Let us understand with an example:
let x = new Date();
today.setHours(0);
alert(x); // the hour changed to 0.
x.setHours(0, 0, 0, 0);
alert(x); // now 00:00:00 sharp.
You can also try this code with Online Javascript Compiler
We can use the getUTC methods for more control over dates and times, which are identical to the get methods except that they calculate time using the UTC standard.
The UTC methods for the JavaScript Date object are listed in the table below:
Date
Method
Range
Year
getUTCFullYear()
YYYY
Month
getUTCMonth()
0-11
Day(month)
getUTCDate()
1-31
Day(week)
getUTCDay()
0-6
Hour
getUTCHours()
0-23
Minute
getUTCMinutes()
0-59
Second
getUTCSeconds()
0-59
Millisecond
getUTCMilliseconds()
0-999
UTC is beneficial because it serves as an international time reference, keeping our code consistent across time zones.
Date.parse method
The parse() method takes a date string and calculates the difference in time since January 1, 1970. It essentially requires a parameter as a string(datestring). It returns a number in milliseconds since January 1, 1970, 00:00:00 UTC.
Syntax:
Date.parse(datestring)
Example:
<script>
// milliseconds in a year
const m = 1000 * 60;
const h = m * 60;
const d = h * 24;
const y = d * 365;
// Compute years
const date = Date.parse("March 25, 2022");
let years = Math.round(date / y);
document.getElementById("demo").innerHTML = years;
</script>
You can also try this code with Online Javascript Compiler
JavaScript, unlike other programming languages, lacks a built-in function for formatting dates.
We can, however, extract individual bits and use them in the manner described below:
const currDate = new Date();
const d = currentDate.getDate();
const m = currentDate.getMonth();
const y = currentDate.getFullYear();
//do (m+1) to give the correct month numbere for use.
let monthDateYear = d + '/' + (m+1) + '/' + y;
console.log(monthDateYear); // 26/10/2021
You can also try this code with Online Javascript Compiler
Here, we format the date ourselves so that it will give an easily readable output and practice by yourself on an online javascript compiler.
Localization Functions of the JavaScript Date Object
If we want to localize the date formatting, we should use the toLocaleDateString() method of the Date object. The toLocaleDateString() method returns a string that represents the date portion of the specified date in the user agent's timezone in a language-sensitive manner.
Each date-time component property's default value is undefined, but if the weekday, year, month, and day properties are all undefined, then a month, year, and day are assumed to be "numeric."
Points to remember:
The Date object in JavaScript is used to represent date and time. Both date and time are always present in the date object together.
The counting of months starts from 0. The days of a week in getDay() are also counted from 0.
There is no built-in date formatting function in JavaScript. We can format it ourselves to increase its readability.
When out-of-range components are set, the date automatically corrects itself.
Dates can be subtracted to get a millisecond difference. When a Date is converted to a number, it becomes a timestamp. To quickly obtain the current timestamp, we use Date.now().
Frequently Asked Questions
Q1) Is there a timezone for JavaScript dates?
Answer: Date objects are UTC (Universal Time Coordinated) and do not have a timezone.
Q2) How do we format a date?
Answer: To improve readability, we can use a slash or a hyphen to format the date. The international standard suggests writing the date as YYYY-MM-DD (year, month, day). So, if both an Australian and an American used this, the date would be 2019-02-03. By putting the year first, this way of writing the date avoids any confusion.
Q3) What happens when the date of the month gets out of range?
Answer: When the date is out of range, the date automatically corrects itself. For example, for January month, the input date is 35, then it will get autocorrected, and the output will be 4 February.
Key Takeaways
In this article, we've learned about JavaScript date and time’s different methods. We have learned the advanced part of date and time in this article. But if you have not gone through our previous article, you must read it to strengthen your basics.
If you want to learn advanced front-end web development, Coding Ninjas has one of the best courses available, which you can find here.