将Java Datetime与当前时间进行比较

时间:2015-04-13 12:40:55

标签: java datetime time calendar

我编写了一个包含org.eclipse.swt.widgets.Datetime的gui程序:

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));

感谢您的帮助!!

亲切的问候

3 个答案:

答案 0 :(得分:1)

我建议您不要添加按钮来发送时间,您可以使用 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
      }
   }
});

答案 1 :(得分:1)

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

    {
        // some method invoked to compare time difference
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, dt.getYear());
        cal.set(Calendar.MONTH, dt.getMonth());
        cal.set(Calendar.DAY_OF_MONTH, dt.getDay());
        cal.set(Calendar.HOUR, dt.getHours());
        cal.set(Calendar.MINUTE, dt.getMinutes());
        cal.set(Calendar.SECOND, dt.getSeconds());

        if (cal.getTimeInMillis() - System.currentTimeMillis() > 30 * 60 * 1000) {
            // the time picked in the DateTime is more than half an hour in
            // the future regarded to the current system time.
        }
    }

答案 2 :(得分:0)

只需检查新创建的Calendar对象是否在当前时间之前的时间值超过1,800,000(即30分钟* 60 * 1000):

如果时间已设置超出限制(以分钟为单位),则以下方法将返回true:

public boolean isOutOfLimit(DateTime dateTime, long minutes) {
    GregorianCalendar now = new GregorianCalendar();
    Calendar chosen = new GregorianCalendar(
            now.get(Calendar.YEAR),
            now.get(Calendar.MONTH),
            now.get(Calendar.DAY_OF_MONTH),
            dateTime.getHours(),
            dateTime.getMinutes(),
            dateTime.getSeconds());
    long millisecs = minutes * 60L * 1000L;
    return ((chosen.getTimeInMillis() - now.getTimeInMillis()) > millisecs) ? true : false;
}