32

Is there any way to convert a date String to LocalDateTime where the format "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$1.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$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.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 String and a DateTimeFormatter and I want to return with LocalDateTime

Is there a correct, nice solution?

EDIT:

My goal, making a method what get a String and a DateTimeFormatter And returns with a LocalDateTime. The Pattern can be anything (what is valid).

LakiGeri
  • 2,046
  • 6
  • 30
  • 56
  • 1
    Use LocalDate or append a dummy hh:ss string (00:00) to your initial one – Ji aSH Mar 13 '17 at 12:00
  • 1
    What is the expected result of parsing, say, `2017-03-13` into a `LocalDateTime`? What if the string and the pattern contain, say, minutes, but neither hours nor seconds? Or the other way around? It seems you have hard requirements. – Ole V.V. Mar 13 '17 at 12:28
  • Does this answer your question? [Parse YYYY-MM-DD dates using the local timezone](https://stackoverflow.com/questions/17893896/parse-yyyy-mm-dd-dates-using-the-local-timezone) – Oswaldo Oct 07 '20 at 18:11
  • @Oswaldo In what way is a JavaScript question a duplicate to a **Java** question? – Mark Rotteveel Oct 07 '20 at 19:56
  • oops, you're right @MarkRotteveel, I didn't notice that. As I found my Javascript answer I wanted to help here too, but haven't noticed it was Java, sorry – Oswaldo Oct 07 '20 at 19:58

6 Answers6

42

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

    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);

or LocalDateTime

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

if you just need an empty timepart

EDIT:

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

    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);
Valentin Michalak
  • 2,089
  • 1
  • 14
  • 27
Jens
  • 67,715
  • 15
  • 98
  • 113
  • Its a good solution I was thinking about it, but what if the dateformatter pattern change to a pattern what contains Hour and Minutes as well? So I want to create a method whats parameters a string and a dateformatter. If the pattern not contain hour and minutes, it should handle, and make LocalDateTime with init (00:00) hour and minutes – LakiGeri Mar 13 '17 at 12:08
  • Working with strings is no good idea. In this case you should use overloded methods – Jens Mar 13 '17 at 12:09
  • Yeah I know.. But in my case it 's necessary, and it will be useful. But I try to solve with other way – LakiGeri Mar 13 '17 at 12:16
27

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

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

after this we can covert it to LocalDateTime

LocalDateTime ldt = ld.atStartOfDay();
Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
  • I understand that, but my goal, making a method what get a `String` and a `DateTimeFormatter` And returns with a `LocalDateTime`. The Pattern can be anything (what is valid). – LakiGeri Mar 13 '17 at 12:13
0

For start of the day you can use:

LocalDate.parse("2017-10-18", DateTimeFormatter.ofPattern("yyyy-MM-dd"))
.atStartOfDay().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"))                        
.atStartOfDay().plusHours(23).plusMinutes(59).plusSeconds(59).atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ISO_DATE_TIME)

For localDateTime 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'"))

Result:

2017-10-18T00:00:00Z
2017-10-18T23:59:59Z
2017-10-18T14:45:35Z
Svenmarim
  • 3,633
  • 5
  • 24
  • 56
Vinayak Shenoy
  • 405
  • 3
  • 9
0

How about a one liner?

LocalDateTime.parse("2017-03-13" + " 00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm"));
Zon
  • 18,610
  • 7
  • 91
  • 99
0

If you have a date in a string with the format "yyyyMMdd" and want to convert into localDate then follow these steps:

public static void processDate() {
    DateTimeFormatter DATEFORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
    LocalDate ld = LocalDate.parse("20200511", DATEFORMATTER);
    System.out.println(ld.toString());
}

The output is in "yyyy-MM-dd" format:

2020-05-11
Atul
  • 3,043
  • 27
  • 39
-1

Use Joda-Time-XX.jar it has DateTimeFormatter to 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.

DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime dateTime =  dateTimeFormatter.parseDateTime(date);
Sandeep
  • 21
  • 1
  • 4
  • 1
    Why external library when you have it in the standard Environment? – Jens Mar 13 '17 at 13:02
  • Can you give a code example for the above, without any external jar? – Sandeep Mar 13 '17 at 13:11
  • It works in java 8 and later versions but what about java 6 or 7? – Sandeep Mar 13 '17 at 15:01
  • The question is about Java-8 as you can see in tags – Jens Mar 13 '17 at 15:02
  • 1
    @Sandeep The Joda-Time project is in maintenance mode, with its team advising migration to the java.time classes. Much of the java.time functionality is back-ported to Java 6 & 7 in the ThreeTen-Backport project. Further adapted for Android in the ThreeTenABP project. – Basil Bourque Mar 13 '17 at 15:14