Node.js中如何将数字日期(如8-1-20)转换为月份字符串格式?
Alright, let's get this date conversion sorted out in Node.js. The task is turning a numeric date string like 8-1-20 into a formatted string with full month names (e.g., 01-August-2020), and your existing code is halfway there—we just need to make sure we properly parse the input string into a valid Date object first, since Intl.DateTimeFormat relies on that.
Step 1: Parse the Numeric Date String
First, the input string (like 8-1-20) needs to be split into its components. We’ll assume your input follows MM-DD-YY (month-day-two-digit-year) for this example; if it’s DD-MM-YY, we’ll adjust that later.
Split the string and convert parts to numbers:
const inputDateStr = "8-1-20"; const [month, day, year] = inputDateStr.split("-").map(Number);
Step 2: Create a Valid Date Object
Remember that JavaScript’s Date uses 0-based months (so January is 0, August is 7). Also, two-digit years need to be expanded to four digits—we’ll assume years 00-49 map to 2000-2049, and 50-99 map to 1950-1999 (adjust this logic if your use case differs):
const fullYear = year >= 50 ? 1900 + year : 2000 + year; const close_date_ = new Date(fullYear, month - 1, day);
Step 3: Format and Clean Up
Your existing formatting code works perfectly—we just run it on the valid Date object, then replace spaces with hyphens to get the final format:
const formatedDate_cd = new Intl.DateTimeFormat('en-GB', { day: '2-digit', month: 'long', year: 'numeric' }).format(close_date_); const finalDate = formatedDate_cd.split(" ").join("-"); console.log(finalDate); // Output: "01-August-2020"
Handling Edge Cases
To make this solution robust, add validation to catch invalid inputs or impossible dates (like February 30th):
function convertNumericDate(input) { const parts = input.split("-").map(Number); if (parts.length !== 3) { throw new Error("Invalid format: Expected MM-DD-YY or DD-MM-YY"); } // Swap these two variables if your input uses DD-MM-YY instead of MM-DD-YY let [month, day, year] = parts; const fullYear = year >= 50 ? 1900 + year : 2000 + year; const date = new Date(fullYear, month - 1, day); // Verify the date is valid (rejects nonsensical dates) if (date.getFullYear() !== fullYear || date.getMonth() !== month - 1 || date.getDate() !== day) { throw new Error("Invalid date"); } const formatted = new Intl.DateTimeFormat('en-GB', { day: '2-digit', month: 'long', year: 'numeric' }).format(date); return formatted.split(" ").join("-"); } // Example usage try { console.log(convertNumericDate("8-1-20")); // "01-August-2020" console.log(convertNumericDate("12-31-99")); // "31-December-1999" } catch (err) { console.error(err.message); }
内容的提问来源于stack exchange,提问作者Sanjay Makwana

