To format a JavaScript date as yyyy-mm-dd (e.g., 2023-05-17), you can use the following code:
function formatDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
// Example usage
const date = new Date();
const formattedDate = formatDate(date);
console.log(formattedDate);
In this code, the formatDate
function takes a Date
object as input and returns the formatted date string in the desired format. It retrieves the year, month, and day components from the Date
object and pads single-digit month and day values with a leading zero if necessary. Finally, it concatenates the components using the desired format pattern (yyyy-mm-dd) and returns the formatted string.
You can replace the new Date()
part in the example usage with any Date
object you want to format, or you can pass a specific date to the formatDate
function.
Comments
Post a Comment