首页 > 解决方案 > 使用 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. 

我该怎么办?

标签: javadatetimemilliseconds

解决方案


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. 如果您想要设备的默认时区,请设置ZONEZoneId.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。请参阅链接。

链接


推荐阅读