JavaScript (JS) is a popular programming language used for creating interactive web pages. One of the important features of JS is its ability to work with dates and times. JS provides various date formats that can be used to display dates and times in different ways. In this article, we will discuss the different date formats available in JS.
JS provides several built-in date formats that can be used to display dates and times. These formats can be used to display the date and time in a way that is easy to read and understand. Some of the commonly used date formats in JS are:
toDateString()
: This method returns the date in a human-readable format, without the time.toTimeString()
: This method returns the time in a human-readable format, without the date.toLocaleDateString()
: This method returns the date in a localized format, based on the user's location.toLocaleTimeString()
: This method returns the time in a localized format, based on the user's location.toISOString()
: This method returns the date and time in ISO format (YYYY-MM-DDTHH:mm:ss.sssZ).These methods can be used with the Date
object in JS to format the date and time in different ways. Let's take a look at some code examples to see how these methods can be used.
Example 1: Using toDateString()
method
<script>
var today = new Date();
document.write("Today's date is: " + today.toDateString());
</script>
Output:
Today's date is: Wed Sep 01 2021
Example 2: Using toTimeString()
method
<script>
var today = new Date();
document.write("The current time is: " + today.toTimeString());
</script>
Output:
The current time is: 12:30:45 GMT+0530 (India Standard Time)
Example 3: Using toLocaleDateString()
method
<script>
var today = new Date();
document.write("Today's date is: " + today.toLocaleDateString());
</script>
Output:
Today's date is: 9/1/2021
Example 4: Using toLocaleTimeString()
method
<script>
var today = new Date();
document.write("The current time is: " + today.toLocaleTimeString());
</script>
Output:
The current time is: 12:30:45 PM
Example 5: Using toISOString()
method
<script>
var today = new Date();
document.write("The date and time in ISO format is: " + today.toISOString());
</script>
Output:
The date and time in ISO format is: 2021-09-01T07:00:45.123Z
JS provides several built-in date formats that can be used to display dates and times in different ways. These formats can be used with the Date
object in JS to format the date and time in a way that is easy to read and understand. By using these formats, developers can create web pages that are more user-friendly and accessible.