我在Java中有字符串timeString = "8:30AM"
。我没有从用户那里得到日期,只有timeString
变量中的具体时间。
我需要将当前日期添加到timeString。
String userTimeString = "8:30AM"; // This is how I get the time from the user
// I need to grab today's date without the hour, and as the hour it should be the userTimeString
// the result should be saved as timeStamp.
你好!
java.time
你需要决定一个时区。一旦您知道了您的时区,我们就可以定义几个常量,例如:
private static final ZoneId ZONE = ZoneId.of("America/Antigua");
private static final DateTimeFormatter TIME_PARSER
= DateTimeFormatter.ofPattern("h:mma", Locale.ENGLISH);
我正在使用java。time,现代Java日期和时间API。将您的时区替换为America/Antigua
。如果您希望您的设备的默认时区,设置ZONE
为ZoneId.systemDefault()
。
现在我们可以:
String userTimeString = "8:30AM";
OffsetDateTime timestamp = ZonedDateTime.of(
LocalDate.now(ZONE),
LocalTime.parse(userTimeString, TIME_PARSER),
ZONE)
.toOffsetDateTime();
System.out.println(timestamp);
我今天跑步时的输出:
2021 - 08 - 30 - t08:30内
是否要在SQL数据库中保存时间戳?从JDBC 4.2开始,您可以将OffsetDateTime
保存到数据类型为timestamp with time zone
的SQL列中。见链接
- Oracle教程:日期时间说明如何使用java.time.
- Stack Overflow回答关于保存java的问题。SQL的时间类型:
- Java/MySQL中没有时间或时区组件的日期,Arvind Kumar Avinash的回答
- 从ResultSet中获取用于java的日期。时间类,我的答案