简体   繁体   English

SWT DateTime-从两个小部件读取日期和时间

[英]SWT DateTime - read date and time from two widgets

Imagine two widgets: 想象两个小部件:

DateTime dtDate = new DateTime(parent, SWT.BORDER);

and

DateTime dtTime = new DateTime(parent, SWT.BORDER | SWT.TIME);

Would would be the most efficient way to read date and time from the two widgets into a single Date variable? 将两个小部件中的日期和时间读入单个Date变量将是最有效的方法吗?

Edit : The following solution that I have in mind is far from being elegant. 编辑 :我想到的以下解决方案远非优雅。 I hope that there is a better way to do this. 我希望有更好的方法可以做到这一点。

final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// year
dateString += String.valueOf(dtDate .getYear());
dateString += "-";
// month
dateString += String.valueOf(dtDate .getMonth());
dateString += "-";

// day
dateString += String.valueOf(dtDate .getDay());
dateString += " ";

// hour
dateString += String.valueOf(dtTime.getHours());
dateString += ":";

// minute
dateString += String.valueOf(dtTime.getMinutes());
dateString += ":";

// second
dateString += String.valueOf(dtTime.getSeconds());

try {
    Date startDate = (Date) dateFormat.parse(dateString);
    } catch (ParseException exception) {
    exception.printStackTrace();
    }

The JFace data binding uses Calendar : JFace数据绑定使用Calendar

Calendar cal = Calendar.getInstance();
cal.clear();

cal.set(Calendar.YEAR, dtDate.getYear());
cal.set(Calendar.MONTH, dtDate.getMonth());
cal.set(Calendar.DAY_OF_MONTH, dtDate.getDay());

cal.set(Calendar.HOUR_OF_DAY, dtTime.getHours());
cal.set(Calendar.MINUTE, dtTime.getMinutes());
cal.set(Calendar.SECOND, dtTime.getSeconds());

Date date = cal.getTime();

If you are using Java 8 you might want to look at using things like LocalDateTime or ZonedDateTime depending on exactly what this date + time represents. 如果您使用的是Java 8,则可能要根据日期和时间的确切含义使用LocalDateTimeZonedDateTime类的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM