Reputation: 39
I'm querying database and getting date in this format "01-SEP-22"
I want to convert this date into this format "yyyy-MM-dd" in Java. Is there any way I can do this.
Upvotes: 0
Views: 776
Reputation: 86323
I recommend that you use java.time, the modern Java date and time API, for your date work.
In order to parse the month abbreviation in all upper case (like SEP
) we need to instruct it to apply case insensitive parsing.
We can use DateTimeFormatterBuilder
to build a DateTimeFormatter
with such an instruction.
private static final DateTimeFormatter oracleFormatter
= new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("dd-MMM-uu")
.toFormatter(Locale.ROOT);
The rest goes smoothly:
String stringFromOracle = "01-SEP-22";
LocalDate date = LocalDate.parse(stringFromOracle, oracleFormatter);
String formattedString = date.toString();
System.out.println(formattedString);
Output is:
2022-09-01
For generating the string I am exploiting the fact that LocalDate.toString()
gives the format that you asked for, so I am not using any formatter explicitly. The format is known as ISO 8601 and as this name says, is an international standard.
String
from Oracle. Retrieve a LocalDate
directly and save the parsing.LocalDate
. If you need to take string input (which is not the case here), parse the string into a LocalDate
immediately. Only when you need to give string output (to the user or in data exchange with another system, for example), format the LocalDate
into a string in the required format.Upvotes: 1
Reputation: 587
You can simply use DateTimeFormatter
:
public String convertDate(String dateStr) throws ParseException {
String[] split = dateStr.split("-");
split[1] = split[1].substring(0, 1).toUpperCase() + split[1].substring(1).toLowerCase();
dateStr = String.join("-", split);
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MMM-yy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(dateStr, dateFormatter);
return date.toString();
}
@Test
public void test_convertDate() throws ParseException {
assertEquals("2022-09-01", convertDate("01-SEP-22"));
}
Upvotes: 0