In this article, you will learn how to transform a Date object into a human-readable string.
Also, you’ll find out how to convert a date to a string in the “yyyy-mm-dd” format.
It only shows the date portion of the date and time component is not included.
The syntax for this method is quite simple:
This method does not take any parameter.
The toDateString() method returns a string representing the date portion of the given date.
This method returns a string in the following format: “Weekday Month Day Year.”
let date = new Date(); console.log(date.toDateString()); ✅
The toDateString() method would return the following output:
Thu Aug 17 2023
Please note that the toDateString() method does not include time information in the output string.
If you need to include time information, you might want to use the toString() or toISOString() methods instead.
The format is as follows:
📌 The first three letters of the weekday (e.g., “Mon” for Monday)
📌 The first three letters of the month (e.g., “Jan” for January)
📌 The two-digit day of the month (e.g., “01” for the first day of the month)
📌 The four-digit year (e.g., “2023”)
So, if you were to use toDateString() on a Date object representing January 1, 2023, it would return the string “Sat Jan 01 2023.”
It creates a new date object for the current date and time.
This method has you covered. It gives you the year of a date as a four-digit number.
This method gives you the day of the month (from 1 to 31).
getHours(), getMinutes(), getSeconds(), getMilliseconds()
These methods give you the hour, minute, second, and millisecond of a date, respectively.
This method is a bit special. It gives you the time in milliseconds since the epoch – midnight on January 1, 1970.
Let’s take a look the the illustration below to convert date to string yyyy-mm-dd:
Here’s the explanation of the example code above:
- We create a new Date object.
- Then, we use the getFullYear(), getMonth(), and getDate() methods to get the year, month, and day of the date.
- We add leading zeros to the month and day if necessary using the slice() method.
- Finally, we concatenate these values into a string in the “yyyy-mm-dd” format.
This method is part of the Date prototype and returns a string that represents only the date portion of a Date object, excluding the time component.
Thank you for reading Itsourcecoders 😊.