如何在Angular中比较ngb日期时间选择器与当前时间?
Hey there! Let's break down how to check if the date and time selected from ngb's pickers is later than the current time. Here's a straightforward approach:
Step 1: Convert Ngb's Date/Time Values to a Native Date Object
First, we need to turn the separate day/month/year (from NgbDatePicker) and hour/minute/second (from NgbTimePicker) into a single Date instance that we can compare with your todayTime.
⚠️ Important Note: Native JavaScript Date uses 0-indexed months (0 = January, 11 = December), but NgbDatePicker returns 1-indexed months (1 = January, 12 = December). So we need to subtract 1 from the Ngb month value when creating the Date.
Here's how to do that:
// Assume these are the values from your pickers const ngbDate = { day: 9, month: 6, year: 2020 }; const ngbTime = { hour: 13, minute: 38, second: 22 }; // Create the selected date-time object const selectedDateTime = new Date( ngbDate.year, ngbDate.month - 1, // Correct for 0-indexed months ngbDate.day, ngbTime.hour, ngbTime.minute, ngbTime.second ); // Your current time const todayTime = new Date();
Step 2: Compare the Two Date Objects
Once you have both Date instances, you can directly compare them using JavaScript's comparison operators (>, <, ===):
// Check if selected time is later than current time if (selectedDateTime > todayTime) { console.log("Selected date-time is later than current time!"); } else if (selectedDateTime.getTime() === todayTime.getTime()) { console.log("Selected date-time is exactly the same as current time!"); } else { console.log("Selected date-time is earlier than current time!"); }
Note: We use getTime() for exact equality checks because direct === compares object references, not the timestamp values.
Bonus: Handle Time Zones (If Needed)
If you're working with UTC time instead of local time, you can use the UTC-based Date constructor methods:
const selectedUTCDateTime = new Date(Date.UTC( ngbDate.year, ngbDate.month - 1, ngbDate.day, ngbTime.hour, ngbTime.minute, ngbTime.second )); const currentUTCTime = new Date(Date.now()); if (selectedUTCDateTime > currentUTCTime) { // Logic for UTC comparison }
That's all! This approach works because native Date objects in JavaScript can be directly compared numerically (they're internally stored as timestamps representing milliseconds since the Unix epoch).
内容的提问来源于stack exchange,提问作者Anjana

