相关疑难解决方法(0)

无法使用Java 8中的DateTimeFormatter和ZonedDateTime从TemporalAccessor获取ZonedDateTime

我最近搬到Java 8,希望更容易处理本地和分区时间.

但是,在我看来,在解析一个简单的日期时,我面临一个简单的问题.

public static ZonedDateTime convertirAFecha(String fecha) throws Exception {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
            ConstantesFechas.FORMATO_DIA).withZone(
            obtenerZonaHorariaServidor());

    ZonedDateTime resultado = ZonedDateTime.parse(fecha, formatter);
    return resultado;
}
Run Code Online (Sandbox Code Playgroud)

就我而言:

  • fecha是'15/06/2014'
  • ConstantesFechas.FORMATO_DIA是'dd/MM/yyyy'
  • obtenerZonaHorariaServidor返回ZoneId.systemDefault()

所以,这是一个简单的例子.但是,解析会抛出此异常:

java.time.format.DateTimeParseException: Text '15/06/2014' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 2014-06-15 of type java.time.format.Parsed
Run Code Online (Sandbox Code Playgroud)

有小费吗?我一直在尝试解析和使用TemporalAccesor的不同组合,但到目前为止没有任何运气.

最好的祝福

java timezone datetime-format java-8 java-time

36
推荐指数
4
解决办法
3万
查看次数

java.time.format.DateTimeParseException:无法在索引处解析文本

这看起来是一件非常简单的事情,但我没有这样做。

我有一个字符串模式,yyyyMMddHH我正在尝试解析2021061104LocalDateTime

这是代码:

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;


class Main {
    public static void main(String[] args) {
        String pattern = "yyyyMMddHH";
        String date = "2021061104";
        DateTimeFormatter formatter =
            new DateTimeFormatterBuilder()
                .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                .parseLenient()
                .appendPattern(pattern)
                .toFormatter();
        LocalDateTime ldt = LocalDateTime.parse(date, formatter);
    }
}
Run Code Online (Sandbox Code Playgroud)

它抛出这个异常:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2021061104' could not be parsed at index 8
        at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
        at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
        at …
Run Code Online (Sandbox Code Playgroud)

java java-time java.time.localdatetime

0
推荐指数
1
解决办法
248
查看次数