Js new date format yyyy mm dd
In JavaScript, you can create a new Date
object and format it as yyyy-mm-dd
using the toISOString()
method or by using a library like Moment.js. Here are a few examples:
Using toISOString()
method
const date = new Date();
const formattedDate = date.toISOString().slice(0, 10);
console.log(formattedDate); // Output: "2023-03-15"
The toISOString()
method returns a string in the format YYYY-MM-DDTHH:mm:ss.sssZ
, but by slicing the string from the beginning to the 10th character, we can get the desired format.
Using Moment.js library
const moment = require('moment');
const date = new Date();
const formattedDate = moment(date).format('YYYY-MM-DD');
console.log(formattedDate); // Output: "2023-03-15"
Moment.js is a popular JavaScript library for working with dates and times. You can use the format()
method to format the date as yyyy-mm-dd
.
Using a custom function
function formatDate(date) {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
}
const date = new Date();
const formattedDate = formatDate(date);
console.log(formattedDate); // Output: "2023-03-15"
This custom function uses the getFullYear()
, getMonth()
, and getDate()
methods to extract the year, month, and day from the Date
object, and then formats them as a string using template literals and the padStart()
method to add leading zeros to the month and day if necessary.