java.time
现代答案:使用现代 Java 日期和时间 API java.time 进行日期和时间工作。早在 2011 年,使用 Timestamp 类是正确的,但从 JDBC 4.2 开始不再建议使用。
对于您的工作,我们需要一个时区和几个格式化程序。我们不妨将它们声明为静态的:
static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");
现在的代码可以是例如:
while(resultSet.next()) {
ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
.atZoneSameInstant(zone);
// I would like to then have the date and time
// converted into the formats mentioned...
String dateFormatted = dtStart.format(dateFormatter);
String timeFormatted = dtStart.format(timeFormatter);
System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
}
示例输出(使用您提出问题的时间):
日期:2011 年 9 月 20 日;时间:18:13 -0400
在您的数据库中,建议将 timestamp with time zone 用于时间戳。如果这是您所拥有的,请像我在代码中所做的那样检索OffsetDateTime。在分别格式化日期和时间之前,我还将检索到的值转换为用户的时区。作为时区,我以 America/Marigot 为例,请提供您自己的时区。当然,如果您不想要任何时区转换,也可以省略。
如果 SQL 中的数据类型只是没有时区的 timestamp,则改为检索 LocalDateTime。例如:
ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
.atZone(zone);
无论细节如何,我相信你会为dtEnd 做类似的事情。
我不确定HH:MM xx 中的xx 是什么意思。我只是将它留在格式模式字符串中,它以小时和分钟为单位生成 UTC 偏移量,不带冒号。
链接: Oracle tutorial: Date Time 解释如何使用 java.time。