Syntax of Date toISOString() Method
The syntax of the Date toISOString() method is defined as:
In this syntax:
- stringVar is the variable in which the program will store the return value from the toISOString()
- dateVar is a Date variable, whose value toISOString() method will convert into string
Additional Notes: The format of the standard, ISO-8601 (in which the string is returned), is “YYYY-MM-DDTHH:mm:ss.sssZ”. The “Z” at the end specifies that the timezone offset is zero.
Example 1: Using a Date Variable Created by an Empty new Date() Constructor
To demonstrate the working of the toISOString() method, simply create a new date variable with the help of the new Date() constructor from the Date object:
Afterwards, apply the toISOString() method on the date variable with the help of a dot operator and then store the return value in a new variable:
Pass the stringVar into the console log function:
The full code snippet will be as:
Upon executing the code mentioned above, the terminal will display the following output:
From the output, it is noticeable that the value of the date variable has been printed in the ISO stand mentioned above.
Example 2: Using a Date Variable With Custom Date in the Constructor
This time around, start by creating a dateString with the following line:
After that, create a new Date variable and pass the dateString in the new Date() constructor with the following line:
Afterwards, apply the toISOString() method on the date variable with the help of a dot operator and then store the return value in a new variable:
Lastly, pass the variable stringVar into the console log function to display the result on the terminal:
The complete code snippet of this example will be as:
dateVar = new Date(dateString);
stringVar = dateVar.toISOString();
console.log(stringVar);
Running this code snippet will produce the following result on the terminal:
The output in the terminal shows the date “15th of February, 2005” in the ISO format.
Wrap up
The Date toISOString() method is used to format the value of a Date variable into a specific ISO format. ISO format is a string representation of a Date value set by the International Organization for Standardization. This toISOString() method returns a string value to the caller. This method was released with the release of the ECMAv5 JavaScript.