Java 8中的日期格式化程序 [英] Date formatter in java 8

查看:102
本文介绍了Java 8中的日期格式化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求,我必须存储带有时区的不同日期和时间. 我已经使用了Java 8的ZonedDateTime.

I have a requirement where i have to store different date and time with time zones. I have used ZonedDateTime of java 8 .

ZoneId zoneId = ZoneId.of("US/Eastern");
ZonedDateTime zt = ZonedDateTime.now(zoneId);

System.out.println(zt.toString());

我的问题是我想以java.util.Date格式存储它. 我用的是DateTimeFormatter

My problem is I want to store this in java.util.Date format. I used DateTimeFormatter

 DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
dtf.format(zt);

直到这里它能正常工作,当我尝试使用简单的日期格式将其转换为java.util.Date时,这给了我所需的字符串格式的日期

Until here it works fine this gives me the required date in string format now when i try to convert this to java.util.Date using simple date format

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
System.out.println(sdf.parse(dtf.format(zt)));

我在IST 2016年3月12日00:44:10获得输出,但我想在java.util.Date类型中将其输出为2016-03-11T14:14:10-05:00.有人可以建议我要去哪里错吗?

I get output as Sat Mar 12 00:44:10 IST 2016 but i want output as 2016-03-11T14:14:10-05:00 in java.util.Date type. Can somebody suggest where am i going wrong?

推荐答案

ZonedDateTime>即时>日期

最好避免使用旧的日期时间类,包括java.util.Date.但是,如果必须,您可以进行转换.调用新的 <旧的java.util.Date类上的c0> 方法.

为此,您需要在UTC时间线上花费Instant时刻.

For that you need an Instant a moment on the timeline in UTC.

Instant instant = myZonedDateTime.toInstant();
java.util.Date juDate = java.util.Date.from( instant );

要走另一个方向:

Instant instant = juDate.toInstant();

这篇关于Java 8中的日期格式化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆