JavaScript date is a function to convert a date string to a parsed date format. It could be a long date format, short date format, medium date format or any other. Here is a JavaScript code to convert date to long date format.
Convert date to long date format
JavaScript is a largely liked and used scripting language throughout the world. Consider code below to convert the date.
const MONTHS = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; const DAYS = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ] function getLongDate(date, format) { let parsedDate = new Date(date); let month = MONTHS[parsedDate.getMonth() + 1]; let day = ''; if(format.indexOf('dddd') > -1) { day = DAYS[parsedDate.getDay()]; } else { day = parsedDate.getDate(); } const dCount = format.split('d').length - 1; if(format.indexOf('MMMM') < 0 || format.indexOf('yyyy') < 0 || (dCount != 1 && dCount != 4)) { return alert('Invalid format provided'); } if(dCount === 4) { return format.replace('MMMM', month) .replace('dddd', day) .replace('yyyy', parsedDate.getFullYear()); } else { return format.replace('MMMM', month) .replace('d', day) .replace('yyyy', parsedDate.getFullYear()); } } const date = getLongDate(new Date(), 'MMMM, dddd yyyy'); console.log(date); alert(date);
Code explanation
I have taken two constant arrays MONTHS
and DAYS
to store the long months and days respectively. I will use them to extract month and day based on the provided date.
The function getLongDate
does all the work. It checks the provided formats and extracts the date, month and year based on them and then return the formatted date.
I have put a condition to check whether the formats provided are correct for the long date or not. If not, I have returned an error message stating that format is invalid.
Code demo
Here is a working code demo in jsFiddle.
Conclusion
JavaScript date is a function which is useful for date string parse and convert it to date. We use the function to format a date as per our requirement.
Read: JavaScript check if a string is binary
Also Read: More JavaScript Articles