在Java中将字符串转换为OffsetDateTime [英] Convert string to OffsetDateTime in Java

查看:3592
本文介绍了在Java中将字符串转换为OffsetDateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试转换 OffsetDateTime 中的字符串,但收到以下错误。

I am trying to convert a string in OffsetDateTime but getting below error.

java.time.format.DateTimeParseException:无法解析文本'20150101':无法从TemporalAccessor获取OffsetDateTime:{},ISO已解析为2015-01-01类型java.time.format.Parsed

代码: OffsetDateTime.parse(20150101,DateTimeFormatter.ofPattern(yyyyMMdd));

预期输出: OffsetDateTime对象,日期20150101。

非常感谢您提供的任何帮助。

I really appreciate any help you can provide.

谢谢,

推荐答案

感谢大家的回复。
之前我使用joda datetime(查看下面的方法)来处理日期和日期时间,但我想使用Java8库而不是外部库。

Thanks everyone for your reply. Earlier I was using joda datetime (look at below method) to handle date and datetime both but I wanted to use Java8 libraries instead of the external libraries.

static public DateTime convertStringInDateFormat(String date, String dateFormat){
    DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat);
return formatter.parseDateTime(date);
}

我期待与OffsetDateTime相同,但知道我们可以使用ZonedDateTime或OffsetDateTime如果我们想在某个时区使用日期/时间。
正在处理LocalDate可以提供帮助的期间和持续时间。

I was expecting same with OffsetDateTime but got to know we can use ZonedDateTime or OffsetDateTime if we want to work with a date/time in a certain time zone. As I am working on Period and Duration for which LocalDate can help.

String to DateTime:

String to DateTime:

LocalDate date =
LocalDate.parse("20150101", DateTimeFormatter.ofPattern("yyyyMMdd"));

LocalDate到所需的字符串格式:

LocalDate to desired string format:

String dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'";
date.atStartOfDay().format(DateTimeFormatter.ofPattern(dateFormat));

这篇关于在Java中将字符串转换为OffsetDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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