我编写了一个带有 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/