如何将yyyy-mm-dd日期转为带序数词的dd month yyyy格式?
How to Implement Month, yyyy Format
stringifyTheDate for yyyy-mm-dd → ddAlright, let's build that stringifyTheDate function you need. Here's a clear breakdown of the required logic, plus a working implementation that handles all edge cases like 11th, 12th, 13th (which don't follow the standard ordinal rules):
Core Logic Steps
- Parse the input date: Split the
yyyy-mm-ddstring into separate year, month, and day components. Remember, the input month is 1-based (e.g., 04 = April), so we'll need to adjust it for zero-indexed arrays later. - Map month numbers to full names: Create an array of month names (January to December) so we can convert the numeric month (like 4) to its full text equivalent ("April").
- Generate ordinal suffixes: Calculate the correct suffix for the day (st, nd, rd, th). Special cases apply for days 11-13—they all use "th" regardless of the last digit.
- Construct the final string: Combine the day + suffix, full month name, and year into the desired format (e.g., "21st April, 2018").
Working Implementation (JavaScript)
function stringifyTheDate(actual_date) { // Split the input into year, month, day (convert to numbers) const [year, month, day] = actual_date.split('-').map(Number); // Full month names (zero-indexed, so month 1 = index 0) const monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; const monthName = monthNames[month - 1]; // Adjust for 1-based input month // Helper function to get ordinal suffix const getOrdinalSuffix = (day) => { if (day >= 11 && day <= 13) return 'th'; switch (day % 10) { case 1: return 'st'; case 2: return 'nd'; case 3: return 'rd'; default: return 'th'; } }; // Combine all parts into the final formatted string return `${day}${getOrdinalSuffix(day)} ${monthName}, ${year}`; } // Test with your example const actual_date = '2018-04-21'; const date = stringifyTheDate(actual_date); console.log(date); // Output: "21st April, 2018"
Notes on Edge Cases
- This handles all tricky ordinal scenarios: 11th, 12th, 13th, 21st, 22nd, 23rd, 31st, etc.
- The function assumes your input is a valid
yyyy-mm-ddstring. If you need to handle invalid inputs, you can add validation checks (e.g., ensuring the month is between 1-12, day is valid for the month/year).
内容的提问来源于stack exchange,提问作者Mukesh Aryal
相关产品推荐
相关产品推荐

