java - 将 Java 日期时间与当前时间进行比较

标签 java datetime time calendar

我编写了一个带有 gui 的程序,其中包含 org.eclipse.swt.widgets.Datetime:

new DateTime(shell, SWT.BORDER | SWT.TIME);

用户可以更改其值以选择特定时间。然后他点击“发送”按钮之类的东西。

当单击此按钮时,我想验证 DateTime 中选取的时间是否比当前系统时间晚半小时以上。

我在 java.util.calender 的帮助下获取系统时间:

Calendar cal = Calendar.getInstance();
cal.get(Calendar.HOUR_OF_DAY);
cal.get(Calendar.MINUTE);
cal.get(Calendar.SECOND));

感谢您的帮助!!

亲切的问候

最佳答案

我建议不要添加一个按钮来发送时间,而是可以使用 SelectionListener 来验证用户选择的时间距当前时间是否大于或小于 30 分钟。您可以查看以下代码:

DateTime timeSelection = new DateTime(shell, DateTime.TIME);
timeSelection.addSelectionListener(new SelectionAdapter (){
   widgetSelected(SelectionEvent e){
      DateTime dateTime = (DateTime)(e.getSource());
      Calendar cal = Calendar.getInstance(); //Create a new instance of Calendar.
      cal.clear(); //Clear all the default values of the calendar object.
      cal.set(dateTime.getYear(), dateTime.getMonth(), dateTime.getDay(), dateTime.getHours(), dateTime.getMinutes(), dateTime.getSeconds()); 
      //Setting all the required fields of the calendar object to the user's selected values. 
      cal.add(Calendar.Minute,-30) //Reduce the user time by 30 minutes so that if we compare the user's time with current time +30 minutes.
      if(cal.after(Calendar.getInstance())){
          //The selected time is more than 30 minutes after current time.
      }else{
          //The selected time is less than current time + 30 minutes
      }
   }
});

关于java - 将 Java 日期时间与当前时间进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29605600/

相关文章:

excel - 宏的运行时间越来越长

java - 什么是 Java 等同于 C++ 的 for_each 模板?

java - java (swing) 中自定义 JButton 中的未知异常

parsing - 将字符串解析为 time.Time 值

android - 如何在 Android 上将持续时间格式化为具有本地化时间单位的字符串?

javascript - 使用日期字符串初始化 javascript 日期对象

java - repaint() 时 JTextArea 不显示,但 revalidate() 时 Graphics 不更新?

java - 如何在 JDBC 中正确初始化创建表 servlet?

python - 如何使用pandas弹出导致错误的日期记录?

java - 为什么我的数组元素不能被正确解析?