java - 使用 AM 或 PM 将今天的日期添加到特定的字符串时间,并将结果作为 timeStamp
问题描述
我有timeString = "8:30AM"
Java中的字符串。我没有从用户那里得到日期,只有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 日期和时间 API java.time。替换您的时区而不是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-30T08:30-04:00
是否要将时间戳保存在 SQL 数据库中?从 JDBC 4.2 开始,您可以将一个保存OffsetDateTime
到数据类型的 SQL 列中timestamp with time zone
。请参阅链接。
链接
- Oracle 教程:日期时间解释如何使用 java.time。
- Stack Overflow 关于将 java.time 类型保存到 SQL 的答案:
- Java/MySQL 中没有时间或时区组件的日期,由 Arvind Kumar Avinash 回答
- 从 ResultSet 中获取日期以用于 java.time 类,我的回答
推荐阅读
- javascript - React:React 如何确保在浏览器有机会绘制之后调用 useEffect?
- mysql - 我是否必须进行 2 次查询才能在 API 中授权用户?
- angular - 使用 NgModel angular 7 进行表单验证
- python - 每当用户在 django rest 框架中发送帖子值时,如何发送 URL 作为响应?
- python - 关闭窗口后进程未完成
- python - 将列表从excel存储到字典中
- android - 如何将表情符号作为带有侦听器的按钮
- elasticsearch - 弹性搜索:查询多个字段
- google-maps-api-3 - 如何放置过滤我的标记的输入
- python - 将我选择的颜色附加到 QPieSeries 的每一片