JavaScript中如何对比当前时间与三个日期并禁用过期日期单选按钮
Alright, let's work through this problem together! You need to validate three specific date-times against the current time in JavaScript, disable their corresponding radio buttons, strike through the date text if it’s in the past, and use a 12-hour format for display. Here’s a complete, actionable solution:
1. Fix Date Parsing (Critical!)
First, the date format you provided (DD/MM/YYYY HH:mm) won’t work with JavaScript’s default new Date() parser (it expects MM/DD/YYYY). We’ll write a helper function to correctly parse these dates:
function parseCustomDate(dateStr) { const [datePart, timePart] = dateStr.split(' '); const [day, month, year] = datePart.split('/').map(Number); const [hours, minutes] = timePart.split(':').map(Number); // Remember: JavaScript months are 0-indexed (Jan = 0, Dec = 11) return new Date(year, month - 1, day, hours, minutes); }
2. Complete the 12-Hour Formatting Function
I’ll finish the snippet you provided to make it fully functional:
function formatAMPM(date) { let hours = date.getHours(); let minutes = date.getMinutes(); const ampm = hours >= 12 ? 'PM' : 'AM'; // Convert 24-hour to 12-hour format hours = hours % 12; hours = hours ? hours : 12; // Handle midnight (0 hours) as 12 // Add leading zero to minutes if needed minutes = minutes.toString().padStart(2, '0'); return `${hours}:${minutes} ${ampm}`; }
3. Main Validation & UI Update Logic
First, let’s assume your HTML looks like this (adjust IDs to match your actual markup):
<div class="date-choice"> <input type="radio" name="selected-date" id="date-a"> <label for="date-a" id="label-a">10/2/2017 11:00</label> </div> <div class="date-choice"> <input type="radio" name="selected-date" id="date-b"> <label for="date-b" id="label-b">21/3/2018 11:20</label> </div> <div class="date-choice"> <input type="radio" name="selected-date" id="date-c"> <label for="date-c" id="label-c">28/4/2018 14:00</label> </div>
Now, the core function to check dates and update the UI:
function validateAndUpdateDates() { const currentTime = new Date(); // List your target dates with their associated element IDs const dateOptions = [ { dateStr: '10/2/2017 11:00', radioId: 'date-a', labelId: 'label-a' }, { dateStr: '21/3/2018 11:20', radioId: 'date-b', labelId: 'label-b' }, { dateStr: '28/4/2018 14:00', radioId: 'date-c', labelId: 'label-c' } ]; dateOptions.forEach(option => { const targetDate = parseCustomDate(option.dateStr); const radioBtn = document.getElementById(option.radioId); const label = document.getElementById(option.labelId); if (targetDate < currentTime) { // Disable the radio button radioBtn.disabled = true; // Strike through the label text label.style.textDecoration = 'line-through'; // Optional: Show 12-hour format alongside original text label.textContent = `${option.dateStr} (${formatAMPM(targetDate)})`; } else { // Ensure future dates are enabled and styled normally radioBtn.disabled = false; label.style.textDecoration = 'none'; label.textContent = `${option.dateStr} (${formatAMPM(targetDate)})`; } }); } // Run validation when the page finishes loading window.addEventListener('load', validateAndUpdateDates); // Optional: Re-validate every minute (in case user stays on page for hours) // setInterval(validateAndUpdateDates, 60000);
Quick Tips
- DOM Matching: Make sure your HTML element IDs exactly match the ones in the JavaScript object list.
- Edge Cases: The parser handles leading zeros (e.g.,
02/10/2017) automatically since we usemap(Number). - Real-Time Checks: Uncomment the
setIntervalline if you want the validation to refresh every minute (useful for long-lived pages).
内容的提问来源于stack exchange,提问作者user7831149

