编写M/D/YYYY转YYYYMMDD日期函数的代码问题排查
Hey there! Let's walk through the problems in your current code and get it working correctly for the YYYYMMDD format requirement.
1. Month Value is Off by One
The biggest problem here is how JavaScript's Date.getMonth() works—it returns a value from 0 to 11 (0 for January, 11 for December). When you pass "12/31/2014" into your function, getMonth() gives you 11 instead of 12, so your output becomes 20141131 instead of the expected 20141231. That's a critical mismatch for the API's required format.
2. Missing Leading Zeros for Single-Digit Months/Days
If someone inputs a date like "1/5/2020" (January 5th), your code will output 202005—which is not only the wrong length (it should be 8 characters) but also misrepresents the month (0 instead of 01). Single-digit months and days need a leading zero to fit the YYYYMMDD structure.
Fixed Code Options
Option 1: Split the String (Most Reliable)
Instead of relying on the Date object's sometimes finicky string parsing, split the input directly. This avoids cross-browser inconsistencies and is more straightforward:
function formatDate(userDate) { // Split the input into month, day, year components const [month, day, year] = userDate.split('/'); // Add leading zeros if needed to make month/day 2 digits const paddedMonth = month.padStart(2, '0'); const paddedDay = day.padStart(2, '0'); // Combine into YYYYMMDD format return `${year}${paddedMonth}${paddedDay}`; } console.log(formatDate("12/31/2014")); // Output: "20141231" console.log(formatDate("1/5/2020")); // Output: "20200105"
Option 2: Fix the Date Object Approach
If you prefer using the Date object, you just need to adjust the month value and add padding for single-digit values:
function formatDate(userDate) { const date = new Date(userDate); const year = date.getFullYear(); // Add 1 to the month to fix the 0-index issue, then pad with zero const month = (date.getMonth() + 1).toString().padStart(2, '0'); // Pad the day with zero if it's a single digit const day = date.getDate().toString().padStart(2, '0'); return `${year}${month}${day}`; } console.log(formatDate("12/31/2014")); // Output: "20141231"
The string-splitting method is generally safer because Date parsing can vary across environments—some might misinterpret date strings in unexpected ways. But both options will get you the correct YYYYMMDD format!
内容的提问来源于stack exchange,提问作者Abde Abde

