gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:27:02 24 4
gpt4 key购买 nike

想象两个小部件:

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

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

将两个小部件中的日期和时间读取到单个日期变量中是否是最有效的方法?

编辑:我想到的以下解决方案远非优雅。我希望有更好的方法来做到这一点。

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

最佳答案

对于 Java 8 及更高版本,您可以使用 LocalDateTime:

LocalDateTime dateTime = 
LocalDateTime.of(dtDate.getYear(), dtDate.getMonth() + 1, dtDate.getDay(), dtTime.getHours(), dtTime.getMinutes(), dtTime.getSeconds());

JFace 数据绑定(bind)使用 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();

关于java - SWT DateTime - 从两个小部件读取日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39752112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com