You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何将带AM/PM的时间字符串拼接当日日期并转换为时间戳

Java实现带AM/PM标识时间拼接当日日期转时间戳方案

推荐使用Java 8及以上版本内置的java.time包实现,线程安全且接口易用,无需引入第三方依赖,实现代码如下:

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class TimeConvertDemo {
    public static void main(String[] args) {
        String userTimeString = "8:30AM";
        
        // 定义12小时制时间解析格式,指定英文Locale适配AM/PM标识,避免中文环境解析失败
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:mma", Locale.US);
        // 解析用户输入的时间字符串为时间对象
        LocalTime inputTime = LocalTime.parse(userTimeString, timeFormatter);
        // 获取当前时区的当日日期(仅包含年月日,无时分秒信息)
        LocalDate today = LocalDate.now(ZoneId.systemDefault());
        // 拼接当日日期和用户输入时间
        LocalDateTime combinedDateTime = LocalDateTime.of(today, inputTime);
        // 转换为对应时区的毫秒级时间戳
        long timestamp = combinedDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        
        System.out.println("拼接后的时间戳:" + timestamp);
    }
}

注意事项

  • 时区配置:如果业务有跨时区需求,不要使用默认系统时区,可显式指定时区,例如国内业务可替换为ZoneId.of("Asia/Shanghai"),避免不同服务器时区差异导致的时间偏移
  • 格式适配:如果用户输入的时间格式存在变化(例如08:30 AM带空格、8:30:00AM带秒数),仅需要调整DateTimeFormatter的格式串即可,比如带空格的格式对应串为"h:mm a"
  • 如果你仍在使用Java 8以前的版本,可使用SimpleDateFormat实现,但需要注意该类线程不安全,多线程环境下需要单独处理

内容的提问来源于stack exchange,提问作者Guisselle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 17:27:01