How can i cut a LocalDateTime format string to limit year from 4 digits to two?

207 views Asked by At

I have a String with a date and time, for example 11/12/2020 10:45, so in this format. I want to cut it so its 7th and 8th character disappear so I get like 11/12/20 10:45. How can i do it? I've been looking to the .split() method of Strings but it don't cut in number of characters but with a regular expression.

1

There are 1 answers

1
rzwitserloot On

I have a String with a date. I want to cut it so its 7 and 8 character dissapear.

This is doable, of course - that is what substring is for. But that's not your problem. Your problem is: I have a date; I wish to render it in a certain fashion. There is a bad way to solve this problem which involves substring, and you're now asking questions about the bad strategy for solving your problem. Let's not bother with answers that support silly directions of solving the underlying problem. split is similarly string manipulation.

Okay, so how do I do this?

Where-ever possible, if you have a well defined concept, then use that. You have the concept of a date. Hopefully it is in the form of an instance of LocalDateTime. If it is not, then let's make that happen:

String input = "2022-12-10 14:10:45";
DateTimeFormatter IN_FORMAT = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
// adjust the pattern to match whatever you have, of course.
LocalDateTime mark = LocalDateTime.parse(input, IN_FORMAT);

Now that we have an LDT instance, the job becomes: Okay, so how do I format this as a string such that only 2 digits are used for the year? That's.. easy.

DateTimeFormatter OUT_FORMAT = DateTimeFormatter.ofPattern("dd-MM-uu HH:mm");
String out = OUT_FORMAT.format(mark);