Can’t rid of ‘T’ in LocalDateTime

There is no T in a LocalDateTime. Date-time objects do not have a “format”.

On the other hand its toString method invariably produces a string with a T in it, per the ISO 8601 standard for text representing date-time values. You cannot change the toString method nor its behaviour.

The way to avoid getting the T is avoiding calling the toString method directly or indirectly. This also means: don’t print the LocalDateTime object and don’t use it in string concatenations.

The facts mentioned so far do no harm in the code you have posted, so I suggest you learn to live it.

EDIT: If I read the first two screen shots linked to from your comments correctly, they show that your debugger shows your LocalDateTime object with a T in it. Your debugger too calls LocalDateTime.toString. There’s no way I could keep my debugger from doing that and hence showing the T, so I don’t expect there is in yours either. You are fighting the wrong problem. I recommend you stop doing that and learn to live with it.

You are correct that you should pass a LocalDateTime as the last argument to busFlightService.search (if departure and arrival are also dates and/or times, I suggest you use an appropriate date/time type for them too rather than strings). So that you can use plusDays inside the method (and similar advantages).

If at some point you need to present the LocalDateTime to a user, you are correct that the user does not want to see the T. You can generate text in any format by using a DateTimeFormatter. That class can even localize the text being generated to represent your LocalDateTime object.

    LocalDateTime dt = LocalDateTime.parse("2015-10-23T03:34:40");
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
            .withLocale(Locale.forLanguageTag("ru"));
    System.out.println(dt.format(formatter));

Output:

23 окт. 2015 г., 3:34:40

Now there’s no T (except the т in окт.). Internally in your program always use LocalDateTime or another appropriate date-time class. Only for presentation use a string.

This separation is widely used and recommended in computing: the one between your model and business logic on one side and user interface and presentation on the other.

PS: As an aside, if you receive the departure time as a string like 2015-10-23 (yyyy-MM-dd), you don’t need to modify the string in order to convert it to LocalDateTime. Either use LocalDate instead or convert like this:

    String departureTime = "2015-10-23";
    LocalDateTime dt = LocalDate.parse(departureTime).atStartOfDay();

Leave a Comment