You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中比较ngb日期时间选择器与当前时间?

How to Compare NgbDatePicker/NgbTimePicker Values with Current Time in Angular

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 21:58:11