Snooze Snoze
Snooze Snoze

Reputation: 109

How to convert String yyyy-MM-ssThh-mm-ss to LocalDataTime yyyy-MM-ss hh-mm-ss?

As in title I have a question. I need to parse LocalDataTime yyyy-MM-ssThh-mm-ss to LocalDataTime yyyy-MM-ss hh-mm-ss but when I do

String beforeConversionStartDate = "2020-01-24T00:06:56";
 private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDataTime parsedDate = LocalDateTime.parse(beforeConversionStartDate,formatter);

Then my output is still yyyy-MM-ddTHH:mm:ss

So my question is how to remove this "T" from LocalDataTime if parser doesn't work properly?

Upvotes: 0

Views: 165

Answers (2)

DavC
DavC

Reputation: 36

LocalDateTime (Java Platform SE 8 ) This function

LocalDateTime.parse(CharSequence text, DateTimeFormatter formatter);

takes in a string with formatted in pattern defined by formatter and returns a LocalDateTime Object, however the returned object is unaware of what what formatter was used. Hence, you will have to format it after you have obtained the parsed your string:

    String str = "1986-04-08 12:30";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
    String newDateTime = formatter.format(dateTime);

Upvotes: 0

Rocherlee
Rocherlee

Reputation: 2801

You are confusing between parse and format method.

  1. First, you want to parse your input to a LocalDateTime instance
  2. Then, you format this instance according to your formatter

    String beforeConversionStartDate = "2020-01-24T00:06:56";
    LocalDateTime parsedDate = LocalDateTime.parse(beforeConversionStartDate);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String formattedDate = parsedDate.format(formatter);
    

Upvotes: 3

Related Questions