0

I am new to Java8 and looking to convert the String into Date in order ro save it in Redis. I went through https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html and tried to Patterns for Formatting and Parsing as per my requirement.

public class DateDemo {
    public static void main(String[] args) {
        DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
        String date = "10-10-2018 12:10:17";
        LocalDateTime parse = LocalDateTime.parse(date, DATE_FORMAT);
        System.out.println("PARSE = "+parse);
    }
}

Output: PARSE = 2018-10-10T12:10:17

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
PAA
  • 1
  • 46
  • 174
  • 282
  • What do you expect the output to be? – Mureinik Dec 05 '18 at 07:04
  • 1
    If you want a LocalDateTime to be displayed in a specific format, and not in the standard ISO format, then you need to format it using that format. It seems you want the date to be displayed as "10-10-2018 12:10:17". In that case, there is no need to parse your string to a LocalDateTime. You already have a string in the desired format. So just use it. – JB Nizet Dec 05 '18 at 07:07
  • @JB Nizet - I want output like : `10-10-2018 12:10:17`, its data type should be `LocalDateTime`. But output showing other way around – PAA Dec 05 '18 at 07:08
  • 5
    An output can't be of type LocalDateTime. An output is a String. You can transform a LocalDateTime to a String using toString() (as you're doing implicitly in your code), and you'll get an ISO output. Or you can transform it to a String using a DateTimeFormatter with a specific format. But a LocalDateTime doesn't have any format. Just like, if you parse the string "one hundred" to an int and print it, you'll get 100, not "one hundred". But you can use a number formatter to redisplay that int as "one hundred". – JB Nizet Dec 05 '18 at 07:12
  • Possible duplicate of [Localdate.format, format is not applied](https://stackoverflow.com/questions/50462041/localdate-format-format-is-not-applied). Or more precisely of [Can’t rid of 'T' in LocalDateTime](https://stackoverflow.com/questions/52311884/can-t-rid-of-t-in-localdatetime). – Ole V.V. Dec 05 '18 at 15:23
  • For one thing that is not possible, as @JBNizet already said. For another, you don’t want that. See the longer explanation in [my answer here](https://stackoverflow.com/a/52485250/5772882). – Ole V.V. Dec 05 '18 at 15:25

0 Answers0