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

如何将String类型日期转换为Long类型?并实现指定日期格式转换

看起来你遇到了两个问题:一是原字符串转long类型时间戳失败,二是想把原日期字符串转成带T和Z的标准格式。先说说为什么你的dateLong一直是0——因为你用的SimpleDateFormat解析模式和输入的dtStart格式不匹配,导致解析抛出异常,date始终是null,dateLong就保持初始值0了。下面一步步解决你的需求:

1. 正确将字符串转换为long类型时间戳

你需要先使用和输入字符串完全匹配的格式来解析日期。输入的dtStart格式是yyyy-MM-dd HH:mm:ss,所以对应的SimpleDateFormat模式应该是这个,而不是带T和Z的。修正后的代码如下:

String dtStart = "2018-04-25 20:09:55";
Date date = null;
long dateLong = 0;
// 使用和输入字符串匹配的解析格式
SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
    date = parseFormat.parse(dtStart);
    dateLong = date.getTime(); // 此时就能得到正确的毫秒级时间戳
    System.out.println(dateLong);
} catch (ParseException e) {
    e.printStackTrace();
}
2. 将原字符串转换为"yyyy-MM-dd'T'HH:mm:ss'Z'"格式

这里提供两种实现方式,推荐使用Java 8及以上版本的新日期API,因为传统的SimpleDateFormat存在线程不安全的问题,新API更稳定可靠。

方式一:使用传统SimpleDateFormat

先解析原字符串为Date对象,再用目标格式的SimpleDateFormat进行格式化:

String dtStart = "2018-04-25 20:09:55";
SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

// 如果需要将时间转换为UTC时区的Z时间,可以设置时区
// targetFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

try {
    Date date = parseFormat.parse(dtStart);
    String formattedDate = targetFormat.format(date);
    System.out.println(formattedDate); // 输出示例:2018-04-25T20:09:55Z
} catch (ParseException e) {
    e.printStackTrace();
}

方式二:使用Java 8+ 新日期API(推荐)

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

String dtStart = "2018-04-25 20:09:55";
// 定义原字符串的解析格式
DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 解析为LocalDateTime对象
LocalDateTime dateTime = LocalDateTime.parse(dtStart, parseFormatter);

// 1. 直接格式化为带Z的字符串(仅作为字符显示)
DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
String formattedDate = dateTime.format(targetFormatter);
System.out.println(formattedDate); // 输出:2018-04-25T20:09:55Z

// 2. 如果需要将时间转换为UTC时区的标准Z格式(Z代表UTC+0)
ZonedDateTime utcDateTime = dateTime.atZone(ZoneId.systemDefault())
                                   .withZoneSameInstant(ZoneOffset.UTC);
String utcFormattedDate = utcDateTime.format(DateTimeFormatter.ISO_INSTANT);
System.out.println(utcFormattedDate); // 输出示例:2018-04-25T12:09:55Z(假设本地时区为东八区)

// 同时获取long类型时间戳
long dateLong = dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
System.out.println(dateLong); // 输出对应的毫秒级时间戳

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:33:44