mrza Nomaan Beg
mrza Nomaan Beg

Reputation: 39

Parse Oracle date to Java

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

Answers (2)

Anonymous
Anonymous

Reputation: 86323

java.time

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.

Suggestions for improvement

  1. Don’t retrieve your date as a String from Oracle. Retrieve a LocalDate directly and save the parsing.
  2. Don’t convert a date from one string format to another. In your program keep the date as a 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.

Links

Upvotes: 1

Domenico Ruggiano
Domenico Ruggiano

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

Related Questions