Java 8 中的日期格式化程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35948266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:47:31  来源:igfitidea点击:

Date formatter in java 8

javajava-8date-formatsimpledateformatdate-formatting

提问by Shaik Mujahid Ali

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

我有一个要求,我必须用时区存储不同的日期和时间。我使用了 java 8 的 ZonedDateTime 。

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

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

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

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

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

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

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

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

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?

我的输出为 Sat Mar 12 00:44:10 IST 2016,但我希望在 java.util.Date 类型中输出为 2016-03-11T14:14:10-05:00。有人可以建议我哪里出错了吗?

回答by Raghu K Nair

You are using a wrong way this is the corrected code

您使用了错误的方式,这是更正的代码

sdf.format(sdf.parse(val)) this the right way.

sdf.format(sdf.parse(val)) 这是正确的方法。

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

    System.out.println(zt.toString());
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
    String val = dtf.format(zt);
    System.out.println(val);

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

回答by Basil Bourque

ZonedDateTime > Instant > Date

ZonedDateTime > 即时 > 日期

Best to avoid the old date-time classes including java.util.Date. But if you must, you can convert. Call the new frommethod on the old java.util.Date class.

最好避免使用旧的日期时间类,包括 java.util.Date。但如果你必须,你可以转换。from在旧的 java.util.Date 类上调用新方法。

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

为此,您需要Instant在 UTC 时间轴上花点时间。

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

To go the other direction:

去另一个方向:

Instant instant = juDate.toInstant();