JavaScript Date.UTC() Method
-
Syntax of JavaScript
Date.UTC()
: -
Example Code: Use
Date.UTC()
to Get the Milliseconds Between the Current Date and January 1970 -
Example Code: Use
Date.UTC()
to Create a Date Object Using UTC Time
The Date.UTC()
method calculates the total number of milliseconds between the reference date and the 1st January 1970 based on the Universal Time Coordinated. We can’t change the syntax in this method and always use Date.UTC()
.
Syntax of JavaScript Date.UTC()
:
Date.UTC(year, month, day, hour, min, sec, milliseconds);
Parameters
year |
The four-digit value is considered the year. It is required. |
month |
An integer should be between 1-11. It is required. |
day |
The integer should be between 1-31. It is optional. |
hour |
An integer should be between 0-23. It is optional. |
min |
The integer should be between 0-59. It is optionally used. |
sec |
An integer should be between 0-59. It can be added when hours and minutes are used. |
milliseconds |
The integer should be between 0-999. It can be added when minutes and seconds are used. |
Return
This method takes a date object and returns the total time difference in milliseconds between the mentioned date and 1st January 1970.
Example Code: Use Date.UTC()
to Get the Milliseconds Between the Current Date and January 1970
While using the Date.UTC()
method, we need to add the year and month as parameters to obtain the difference in milliseconds between the two dates. In this example, we used the Date.UTC()
method to get the total number of milliseconds between the two dates, according to UTC.
let utc = Date.UTC(2022,8,19);
console.log(utc);
Output:
1663545600000
Example Code: Use Date.UTC()
to Create a Date Object Using UTC Time
We use the JavaScript Date.UTC()
method to create a date object according to the UTC rather than the local time. In this example, we have created a date object using the new Date()
and Date.UTC()
methods.
<html>
<body>
<p id="code"></p>
<script>
const d = new Date(Date.UTC(2022,8,19));
document.getElementById("code").innerHTML = d;
</script>
</body>
</html>
Output:
Sun Sep 18 2022 17:00:00 GMT-0700 (Pacific Daylight Time)
The date.UTC()
method works on all browsers.