-1

I've a problem with date. I've a date as string in format: "2017-05-10 16:30" I'd like to convert it to date looking the same as I wrote before. Please help me, thanks in advance!

stash
  • 47
  • 5
  • 2
    First of all, have you investigated [`DateTimeFormatter`](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html)? Second of all, that's not how date/time objects work. Date/time objects are containers for the amount of time which has passed from a given point in time, they don't carry any formatting of their own, that's what things like [`DateTimeFormatter`](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) are for, they take a date/time` object and generate text representation based on the supplied format – MadProgrammer May 04 '17 at 01:32
  • 2
    [Change date format in a Java string](http://stackoverflow.com/questions/4772425/change-date-format-in-a-java-string/4772461#4772461) may also help – MadProgrammer May 04 '17 at 01:40
  • The simple trick is to use the same `DateTimeFormatter` for converting both ways. It will convert your `String` to a `LocalDateTime` and your `LocalDateTime` to a `String` looking the same. – Ole V.V. May 04 '17 at 06:17

2 Answers2

0

A simple search in google or stackoverflow might lead to answer but here you go.

Pre Java 8

Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2017-05-10 16:30");

Java 8

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime ldt = LocalDateTime.parse("2017-05-10 16:30", dtf);
Chris
  • 448
  • 2
  • 8
  • 1
    *"A simple search in google or stackoverflow"* - Then I'd suggest you vote to close the question as a duplicate to encourage the OP to actual do that next time - I'd also suggest that in this day and age, we should be recommending `DateTimeFormatter` over the now defunct `SimpleDateFormat` – MadProgrammer May 04 '17 at 01:34
0

You can use LocalDateTime.parse to create a LocalDateTime object, but the second part of your question didn't really make sense. The date object itself doesn't have a format, so it can't "look like" anything. You decide what format to adopt when you convert it back to a string.

John Angland
  • 446
  • 3
  • 12