Java获取本地UTC时间戳以及格式化

Java获取本地UTC时间戳最简单方式

以下提供一种最简单的实现方式

//获取UTC时间戳(毫秒级)
long utcTime = System.currentTimeMills();

大多数初学者使用过new Date() 的方式

Date date = new Date();
long utcTime = date.getTime();

其实内部实现方式还是调用System中的方法,查看源码可知:

pbulic Data() {
	this(System.currentTimeMills());
}

所以建议,获取本地时间戳还是直接使用System中方法即可
当然java中还有其他函数去获取时间戳的方式,比如Calendar

Calendar cal = Calendar.getInstance();
//获取UTC时间戳(毫秒级)
long utcTime=cal.getTimeInMillis();

UTC时间格式化

public String utcFormat(Long utcTime) {
    DateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    return dft.format(utcTime);
}

该方法在并发场景中,可能会出现多线程问题
规避方法:

private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
public String utcFormat(Long utcTime) {
	synchronized (DATE_FORMAT) {
       	return dft.format(utcTime);
	}
}
<think>好的,用户现在问的是如何用Java格式化时间戳。之前他们遇到了Timer未定义的问题,现在转向时间处理,可能是在开发Swing应用时需要显示时间。首先,我需要确认时间戳是指的秒级还是毫秒级的,通常Java里System.currentTimeMillis()返回的是毫秒级的时间戳。 接下来,用户可能需要将长整型的时间戳转换为可读的日期时间格式。这时候需要用到SimpleDateFormat或者Java 8的DateTimeFormatter。考虑到用户可能使用的Java版本,如果是较旧的版本,比如Java 7或以下,那么SimpleDateFormat是主要选择,但要注意线程安全问题。如果是Java 8及以上,推荐使用新的java.time API,比如LocalDateTime和DateTimeFormatter,这些类是不可变的,线程安全,而且API更清晰。 然后,我需要给出具体的示例代码,包括两种方式的处理:旧版和新版。同时要指出时区的问题,因为时间戳通常是UTC时间,转换为字符串时可能需要设置时区,特别是当用户需要本地时间显示的时候。例如,SimpleDateFormat的setTimeZone方法,或者Java 8中的ZoneId。 另外,用户可能还会遇到格式化字符串的写法问题,比如yyyy代表年份,MM代表月份,HH是24小时制,hh是12小时制,ss是秒等等。需要提醒用户注意大小写的不同含义,避免常见的错误,比如误用mm表示月份(实际是分钟)。 还有,解析字符串到时间戳的情况,用户可能需要反向操作,这时候同样需要提供示例,比如SimpleDateFormat的parse方法,或者Java 8中的LocalDateTime.parse配合DateTimeFormatter。 可能还需要提到处理异常的情况,比如ParseException,建议用户进行适当的异常处理,避免程序崩溃。同时,提醒SimpleDateFormat不是线程安全的,如果在多线程环境下使用,需要采取同步措施或者使用ThreadLocal。 最后,总结推荐使用Java 8的新API,因为它更现代,功能更强大,而且避免了旧API的一些坑。如果用户必须使用旧版本,再详细说明SimpleDateFormat的用法和注意事项。</think>在Java格式化时间戳主要通过日期时间API实现,以下是不同Java版本的推荐方案: --- ### 方案一:Java 8+ 新版API(推荐) ```java import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; public class TimestampFormat { public static void main(String[] args) { // 获取当前时间戳(毫秒) long timestamp = System.currentTimeMillis(); // 转换为可读格式 DateTimeFormatter formatter = DateTimeFormatter .ofPattern("yyyy-MM-dd HH:mm:ss") .withZone(ZoneId.systemDefault()); // 使用系统默认时区 String formatted = formatter.format(Instant.ofEpochMilli(timestamp)); System.out.println("格式化结果: " + formatted); } } ``` --- ### 方案二:旧版Java(<8)使用SimpleDateFormat ```java import java.text.SimpleDateFormat; import java.util.Date; public class OldTimestampFormat { public static void main(String[] args) { long timestamp = System.currentTimeMillis(); // 注意:SimpleDateFormat非线程安全 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setTimeZone(TimeZone.getDefault()); // 设置时区 String formatted = sdf.format(new Date(timestamp)); System.out.println("格式化结果: " + formatted); } } ``` --- ### 格式化模式符号对照表 | 符号 | 含义 | 示例 | |------|-----------------------|------------| | y | 年份 | 2023 | | M | 月份(1-12) | 07 | | d | 日期(1-31) | 25 | | H | 24小时制小时(0-23) | 15 | | h | 12小时制小时(1-12) | 03 | | m | 分钟(00-59) | 45 | | s | 秒钟(00-59) | 30 | | S | 毫秒(000-999) | 789 | | a | 上午/下午标记 | PM | | z | 时区 | GMT+08:00 | --- ### 时间戳转换场景示例 #### 1. 时间戳 ➔ 字符串 ```java // Java 8+ String result = Instant.ofEpochMilli(1687856789000L) .atZone(ZoneId.of("Asia/Shanghai")) .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); // 旧版Java String result = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z") .format(new Date(1687856789000L)); ``` #### 2. 字符串 ➔ 时间戳 ```java // Java 8+ long timestamp = LocalDateTime.parse("2023-06-25T15:30:45", DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toInstant() .toEpochMilli(); // 旧版Java long timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .parse("2023-06-25 15:30:45") .getTime(); ``` --- ### 时区处理技巧 ```java // 转换为纽约时间 DateTimeFormatter nyFormatter = DateTimeFormatter .ofPattern("yyyy-MM-dd hh:mm:ss a") .withZone(ZoneId.of("America/New_York")); // 转换为UTC时间 String utcTime = Instant.now().atZone(ZoneOffset.UTC) .format(DateTimeFormatter.ISO_INSTANT); ``` --- ### 性能优化建议 1. **重用格式化对象**(线程安全方式): ```java // Java 8+ 使用不可变对象 private static final DateTimeFormatter CACHED_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 旧版Java使用ThreadLocal private static final ThreadLocal<SimpleDateFormat> threadLocalFormat = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd")); ``` 2. 使用预定义格式: ```java // ISO标准格式(如:2023-06-25T15:30:45.123Z) String isoFormat = Instant.now().toString(); ``` --- ### 常见问题解决 **Q:为什么时间显示少8小时?** A:未正确设置时区,需要指定时区: ```java // 设置东八区(北京时间) formatter.withZone(ZoneId.of("GMT+8")); ``` **Q:解析时出现ParseException?** A:确保模式与输入字符串严格匹配: ```java // 输入包含毫秒时需要对应模式 DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值