java dateformat 时区,Java DateFormat parse()不遵守时区

本文探讨了在Java中使用Calendar和DateFormat处理日期时间时,时区转换出现的问题。当从format()方法获取日期并进行parse()操作时,结果并未保持时区设置。原因在于Date对象本身不包含时区信息,它表示的是一个时间点。解决方案是再次使用相同的DateFormat进行格式化以确保一致性。此外,建议在复杂的日期时间操作中使用JodaTime库,因为它的API更友好。
摘要由CSDN通过智能技术生成

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"));

DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");

df.setTimeZone(TimeZone.getTimeZone("America/New_York"));

try {

System.out.println(df.format(cal.getTime()));

System.out.println(df.parse(df.format(cal.getTime())));

} catch (ParseException e) {

e.printStackTrace();

}

Here is the result:

2011-09-24 14:10:51 -0400

Sat Sep 24 20:10:51 CEST 2011

Why when I parse a date I get from format() it doesn't respect the timezone?

解决方案

You're printing the result of calling Date.toString(), which always uses the default time zone. Basically, you shouldn't use Date.toString() for anything other than debugging.

Don't forget that a Date doesn't have a time zone - it represents an instant in time, measured as milliseconds since the Unix epoch (midnight on January 1st 1970 UTC).

If you format the date using your formatter again, that should come up with the same answer as before.

As an aside, I would recommend the use of Joda Time instead of Date/Calendar if you're doing any significant amount of date/time work in Java; it's a much nicer API.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值