Here's a JavaScript function that checks if a string is in the "yyyy-mm-dd" format and, if so, converts it into a human-readable format based on the user's locale:
javascript
function formatDate(dateString) {
// Regular expression pattern for yyyy-mm-dd format
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
// Check if the string matches the yyyy-mm-dd format
if (!datePattern.test(dateString)) {
return "Invalid date format. Please use yyyy-mm-dd.";
}
// Create a Date object from the input string
const date = new Date(dateString);
// Get the user's locale
const locale = navigator.language || navigator.userLanguage;
// Convert the date to a human-readable format based on the user's locale
const formattedDate = date.toLocaleDateString(locale, {
year: "numeric",
month: "long",
day: "numeric"
});
return formattedDate;
}
Explanation:
The function formatDate takes a dateString parameter, which is the string to be checked and formatted.
We define a regular expression pattern datePattern that matches the "yyyy-mm-dd" format. It ensures that the string consists of four digits for the year, followed by a hyphen, two digits for the month, another hyphen, and two digits for the day.
We use the test method of the regular expression to check if the dateString matches the datePattern. If it doesn't match, we return an error message indicating that the date format is invalid.
If the dateString passes the format check, we create a new Date object by passing the dateString to the Date constructor. This converts the string into a valid date object.
We retrieve the user's locale using navigator.language or navigator.userLanguage. This gives us the preferred language and region settings of the user's browser.
We use the toLocaleDateString method of the Date object to convert the date into a human-readable format based on the user's locale. We pass the locale as the first argument and an options object as the second argument. The options object specifies that we want the year in numeric format, the month in long format (e.g., "January"), and the day in numeric format.
Finally, we return the formattedDate, which is the date string formatted according to the user's locale.
Example usage:
javascript
console.log(formatDate("2023-06-08")); // Output: "June 8, 2023" (for en-US locale)
console.log(formatDate("2023/06/08")); // Output: "Invalid date format. Please use yyyy-mm-dd."
In the example, if the input string is in the correct "yyyy-mm-dd" format, the function will return the date in a human-readable format based on the user's locale. If the input string is not in the correct format, an error message will be returned.