合并日期时间字符串的方法无法正常运行,寻求技术排查
Fixing Your
mergeTime Method Let's break down why your current mergeTime function isn't working, then fix it step by step.
The Core Issues in Your Current Code
Looking at your implementation, there are a few critical problems causing the date parsing to fail:
- Wrong date method:
date.getDay()returns the day of the week (0 = Sunday, 6 = Saturday), not the day of the month. You needdate.getDate()instead. - Off-by-one month:
date.getMonth()returns a 0-indexed value (0 = January, 11 = December), so you need to add 1 to get the correct calendar month. - Unpadded time values: If hours/minutes are less than 10 (e.g., 9 AM or 5 minutes past the hour), they'll render as single digits (like
9:5), which can break date string parsing. - Fragile string concatenation: Manually building date strings is error-prone—using native Date methods to set time is more reliable.
Fixed Implementation
Here's a revised version of your function that addresses all these issues:
mergeTime(time, date) { console.log(time); console.log(date); // Create a copy of the date to avoid modifying the original object const mergedDate = new Date(date); // Set the hours, minutes, and seconds from the time object mergedDate.setHours(time.getHours()); mergedDate.setMinutes(time.getMinutes()); mergedDate.setSeconds(0); console.log(mergedDate); return this.timestamp(mergedDate); }
Why This Works
- No string parsing needed: Instead of building a custom date string, we directly modify a copy of the input date using
setHours,setMinutes, andsetSeconds. This avoids all the formatting pitfalls of manual string concatenation. - Preserves original objects: By creating a new Date instance from the input
date, we don't accidentally mutate the original date object passed into the function. - Handles all time values correctly: Native Date methods automatically handle padding for hours/minutes (e.g., 9 AM becomes
09internally, no extra code needed).
Alternative: Fixed String Concatenation (If You Prefer)
If you still want to build the date string manually (though the above method is better), here's how to fix your original approach:
mergeTime(time, date) { console.log(time); console.log(date); // Fix: Use getDate() for day of month, add 1 to getMonth() const dateString = `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`; // Fix: Pad hours/minutes with leading zero if needed const paddedHours = String(time.getHours()).padStart(2, '0'); const paddedMinutes = String(time.getMinutes()).padStart(2, '0'); const timeString = `${paddedHours}:${paddedMinutes}:00`; const merged = new Date(`${dateString} ${timeString}`); console.log(merged); return this.timestamp(merged); }
Just note that date string formats can vary by locale, so the first method (using Date setter functions) is more cross-browser and locale-safe.
内容的提问来源于stack exchange,提问作者Sandra Willford
相关产品推荐
相关产品推荐

