Java 将字符串 "yyyy-MM-dd" 转换为 LocalDateTime

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42763103/
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-08-12 00:22:16  来源:igfitidea点击:

convert String "yyyy-MM-dd" to LocalDateTime

javadatejava-8date-parsing

提问by LakiGeri

Is there any way to convert a date Stringto LocalDateTimewhere the format "yyyy-MM-dd"?

有什么办法转换的日期StringLocalDateTime了格式"yyyy-MM-dd"

If I try this:

如果我试试这个:

DateTimeFormatter DATEFORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDateTime ldt = LocalDateTime.parse(string, DATEFORMATTER);

I got this exception:

我得到了这个例外:

java.time.format.DateTimeParseException: Text '2017-03-13' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2017-03-13 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at hu.npsh.workforce.utils.Util.stringToLocalDateTime(Util.java:284)
    at hu.npsh.workforce.utils.util.StringLocalDateTimeConversionTest.stringToLocalDateTimeTest(StringLocalDateTimeConversionTest.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access
    DateTimeFormatter DATEFORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDate ld = LocalDate.parse("2017-03-13", DATEFORMATTER);
    LocalDateTime ldt = LocalDateTime.of(ld, LocalDateTime.now().toLocalTime());
    System.out.println(ldt);
0(ParentRunner.java:58) at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2017-03-13 of type java.time.format.Parsed at java.time.LocalDateTime.from(LocalDateTime.java:461) at java.time.format.Parsed.query(Parsed.java:226) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) ... 26 more Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {},ISO resolved to 2017-03-13 of type java.time.format.Parsed at java.time.LocalTime.from(LocalTime.java:409) at java.time.LocalDateTime.from(LocalDateTime.java:457) ... 28 more

I know that the main problem, that the pattern does not contain the hour and the minute.. But what if I want a create a method what gets a Stringand a DateTimeFormatterand I want to return with LocalDateTime

我知道主要问题是模式不包含小时和分钟..但是如果我想要创建一个方法来获取 aString和 aDateTimeFormatter并且我想返回LocalDateTime

Is there a correct, nice solution?

有没有正确的,好的解决方案?

EDIT:

编辑:

My goal, making a method what get a Stringand a DateTimeFormatterAnd returns with a LocalDateTime. The Pattern can be anything (what is valid).

我的目标是创建一个方法来获取 aString和 aDateTimeFormatter并且返回 a LocalDateTime。模式可以是任何东西(什么是有效的)。

采纳答案by Jens

Use LocalDateto create a localDate and then you can add the timepart if you need it:

使用LocalDate创建LOCALDATE的,然后如果你需要它,你可以添加timepart:

ldt = LocalDateTime.of(ld, LocalDateTime.MIN.toLocalTime());

or LocalDateTime

或者 LocalDateTime

    DateTimeFormatter DATEFORMATTER1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    DateTimeFormatter DATEFORMATTER = new DateTimeFormatterBuilder().append(DATEFORMATTER1)
    .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
    .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
    .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
    .toFormatter();

    //DateTimeFormatter DATEFORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDateTime ldt = LocalDateTime.parse("2017-03-13", DATEFORMATTER);

if you just need an empty timepart

如果你只需要一个空的时间段

EDIT:

编辑:

Look at this solution with this you can build your dynamic parser:

看看这个解决方案,你可以构建你的动态解析器​​:

DateTimeFormatter dateformatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate ld = LocalDate.parse("2017-03-13", dateformatter);

回答by Anton Balaniuc

You can not convert "2017-03-13" to a LocalDateTimesince there is no time information in the string, only date. You can convert it to a LocalDate

您不能将“2017-03-13”转换为 a,LocalDateTime因为字符串中没有时间信息,只有日期。您可以将其转换为LocalDate

LocalDateTime ldt = ld.atStartOfDay();

after this we can covert it to LocalDateTime

在此之后,我们可以将其转换为 LocalDateTime

DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime dateTime =  dateTimeFormatter.parseDateTime(date);

回答by Sandeep

Use Joda-Time-XX.jarit has DateTimeFormatterto convert date to date time format. Either you can provide date time in (yyyy-MM-dd HH:mm:ss format) or date alone. In both the cases you will get date and time.

使用Joda-Time-XX.jar它有DateTimeFormatter将日期转换为日期时间格式。您可以以(yyyy-MM-dd HH:mm:ss 格式)或单独的日期提供日期时间。在这两种情况下,您都将获得日期和时间。

LocalDate.parse("2017-10-18", DateTimeFormatter.ofPattern("yyyy-MM-dd"))
.atStartOfDay().atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ISO_DATE_TIME)

回答by Vinayak Shenoy

For start of the day you can use:

对于一天的开始,您可以使用:

LocalDate.parse("2017-10-18", DateTimeFormatter.ofPattern("yyyy-MM-dd"))                        
.atStartOfDay().plusHours(23).plusMinutes(59).plusSeconds(59).atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ISO_DATE_TIME)

For end of the day you can use:

在一天结束时,您可以使用:

LocalDate.parse("2017-10-18", DateTimeFormatter.ofPattern("yyyy-MM-dd")).atTime(LocalTime.now())
.atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"))

For localDateTime you can use:

对于 localDateTime,您可以使用:

2017-10-18T00:00:00Z
2017-10-18T23:59:59Z
2017-10-18T14:45:35Z

Result:

结果:

LocalDateTime.parse("2017-03-13" + " 00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm"));

回答by Zon

How about a one liner?

一个班轮怎么样?

##代码##