如何使用TimeZone将String转换为Date? [英] How to convert String to Date with TimeZone?

查看:671
本文介绍了如何使用TimeZone将String转换为Date?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在日期 +时区中转换我的字符串
我从 DateTime 变量(这里:xyz)获取我的字符串。
我的代码:

I'm trying to convert my String in Date + Timezone. I get my String from a DateTime Variable (here: xyz). My code:

String abc = xyz.toString("yyyy-MM-ddZZ");
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-ddXXX");
java.util.Date date = sdf.parse(abc);
System.out.println("Date: " + sdf.format(date));

错误:


格式无效:2017-01-03 + 01:00格式错误为+01:00

Invalid format: "2017-01-03+01:00" is malformed at "+01:00"

如果我尝试 SimpleDateFormat(yyyy-MM-dd); 它有效,但没有时区(+01:00)

If I try SimpleDateFormat("yyyy-MM-dd"); it works but without the Timezone ("+01:00")

推荐答案

输入有一个日期 - 年,月,日 - 和一个偏移 - 与UTC的区别 - 但要构建 java.util.Date ,您还需要时间:小时,分钟,秒,小数秒。

The input has a date - year, month, day - and an offset - the difference from UTC - but to build a java.util.Date, you also need the time: hour, minutes, seconds, fraction of seconds.

SimpleDateFormat 非常糟糕,因为它有一些魔力,将缺少的字段设置为默认值值。另一个问题是 X 模式不适用于所有Java版本,文档也很糟糕。

SimpleDateFormat is terrible because it does some "magic", setting the missing fields to default values. Another problem is that the X pattern doesn't work for all Java versions, and the documentation sucks.

你可以使用新的Java 8类,如上所述。使用它们,您可以解析输入,选择要用于时间字段的默认值,并转换为 java.util.Date ,如果这是您需要的:

You can use the new Java 8 classes, as explained. With them, you can parse the input, choose the default values to be used for the time fields and convert to java.util.Date, if that's what you need:

DateTimeFormatter fmt = new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_OFFSET_DATE)
    // set hour to midnight
    .parseDefaulting(ChronoField.HOUR_OF_DAY, 0).toFormatter();

OffsetDateTime odt = OffsetDateTime.parse("2017-01-03+01:00", fmt); // 2017-01-03T00:00+01:00

OffsetDateTime 将时间设置为午夜,但您可以将其更改为您需要的任何值,而使用 SimpleDateFormat 则不可能,因为它使用内部默认值,您无法控制它。

The OffsetDateTime will have the time set to midnight, but you can change it to whatever values you need, while with SimpleDateFormat it's not possible, because it uses internal default values and you can't control it.

并且日期和偏移量已正确设置为输入字符串中的值。然后,如果需要,您可以转换为 java.util.Date

And the date and offset were correctly set to the values in the input string. You can then convert to java.util.Date if you want:

Date date = Date.from(odt.toInstant());

如果需要,您还可以获得日期的各个部分:

You can also get the individual "pieces" of the date if you want:

// get just the date
LocalDate localDate = odt.toLocalDate(); // 2017-01-03
// get just the offset
ZoneOffset offset = odt.getOffset(); // +01:00

PS:偏移量 +01:00 与时区相同。查看差异此处

PS: the offset +01:00 is not the same thing as a timezone. See the difference here

这篇关于如何使用TimeZone将String转换为Date?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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