JS中三元运算符赋值当前日期及日期比较问题排查
Hey Antonio, let's break down why your date comparison code isn't behaving as expected and fix it properly:
核心问题所在
错误的日期字符串拼接
Your current way of concatenating date parts (today.getDate().toString().concat(...)) creates a messy string like"1552024"for May 15, 2024. This format doesn't match standard date strings (like"2024-05-15"or"05/15/2024"), so when you try to compare it with the input value, the comparison will fail because the formats are incompatible.不严谨的空值判断
The!$("#" + fieldIdStart).val()check only catches empty strings, but it won't handle cases where the input has whitespace (like spaces). Plus, it doesn't explicitly account for scenarios where the field might not exist (thoughval()would returnundefinedhere, which!would still catch, but it's better to be explicit).
修复后的代码
Here's the corrected version with explanations:
function CompareDate(fieldIdStart, fieldIdEnd) { // Generate today's date in a standard YYYY-MM-DD format (adjust if your input uses a different format) const today = new Date(); const year = today.getFullYear(); // Use padStart to ensure month/day are 2 digits (e.g., "05" instead of "5") const month = String(today.getMonth() + 1).padStart(2, '0'); const day = String(today.getDate()).padStart(2, '0'); const todayFormatted = `${year}-${month}-${day}`; // Get and trim the start date input value to handle whitespace const startInputVal = $.trim($("#" + fieldIdStart).val()); // Fallback to today's date if input is empty/whitespace const dateStart = startInputVal === "" ? todayFormatted : startInputVal; // Repeat the same logic for end date if needed const endInputVal = $.trim($("#" + fieldIdEnd).val()); const dateEnd = endInputVal === "" ? todayFormatted : endInputVal; // Convert to Date objects for reliable comparison const startDate = new Date(dateStart); const endDate = new Date(dateEnd); // Example comparison logic: check if start date is after end date if (startDate > endDate) { console.log("Start date cannot be later than end date!"); return false; } // Add your other comparison logic here... return true; }
关键改进点
- 标准日期格式:By formatting today's date into
YYYY-MM-DD(with leading zeros for month/day), you ensure it matches the format most date input fields use. If your input usesMM/DD/YYYY, just adjust the format to${month}/${day}/${year}. - Robust empty check:Using
$.trim()removes any accidental whitespace from the input, so a field with just spaces will be treated as empty. - Date object comparison:Converting the strings to
Dateobjects makes comparisons far more reliable than comparing raw strings—JavaScript can properly parse standard date formats and handle the comparison logic correctly.
内容的提问来源于stack exchange,提问作者Antonio Craveiro

