. Advertisement .
..3..
. Advertisement .
..4..
As usual, we make sure that you should format a date in particular formats as both the backend and frontend demand. Transforming dates can be accessible at this time. This blog will show you how to format a date as ‘YYYY-MM-DD’ using Javascript. Let’s take a look at around great information below.
How to format a date as YYYY-MM-DD using Javascript
We will simply present the main approaches below to help you format a date as YYYY-MM-DD using Javascript.
Use toISOString()
Syntax: Date.toISOString()
Parameters: None
As for this method, it might not take the parameter. It can be used with the Date object made using the Date() constructor.
This method assists you in converting date strings into simplified format (YYYY-MM-DDTHH:mm:ss.sssZ)
We made a short function that gets a date as “YYYYMMDD.” Besides, the split method gets a pattern and splits the string.
function formatYYYYMMDD(varDate = new Date()) {
return varDate.toISOString().split('T')[0];
}
var testDate = new Date('Tuesday, August 30, 2022');
console.log(formatYYYYMMDD(testDate)); // "2022-08-29"
console.log(formatYYYYMMDD()); // "2022-09-01"
Use toLocaleDateString()
Syntax: toLocaleDateString(locales, options)
Parameters:
- Locales: A string with the BCP 47 language tag or the array of strings.
- Options: The object customizes the output format.
The code below represents a one-liner hack you might use.
console.log(new Date().toLocaleDateString('sv')); // 2022-09-01
Extract the parts of the date and merge them
As for this solution, you need to split the three items below. Next, you put them together. Here is the specific detail that you need to know before using them.
In this case, you have to use three related methods:
- Syntax:
Date.getFullyear()
- Parameters: None
This method will return a number showing the year based on the given date.
- Syntax:
Date.getMonth()
- Parameters: None
This method will return value from January to December.
- Syntax:
Date.getDate()
- Parameters: None
This method will return the number range from 1 to 31.
Afterward, you should ensure the outcome usually consists of double digits for dates and months so that we can fix it by applying the padStart function.
- Syntax:
padStart(targetLength, padString)
- Parameters:
- targetLength: whole length of a string.
- padString: a string pads to the given string.
Here is the illustrated code below.
function formatYYYYMMDD(vardate = new Date()) {
let year = vardate.getFullYear();
let month = (vardate.getMonth()+1).toString().padStart(2, '0');
let date = vardate.getDate().toString().padStart(2, '0');
return `${year}-${month}-${date}`;
}
console.log(formatYYYYMMDD()); // 2022-09-01
Conclusion
You can use all the leading approaches above to format a date as YYYYMMDD using Javascript. Last but not least, leave your comment below this blog if needed.
Read more:
Leave a comment