Help / Tips for manipulating dates and formats by reading them with a BufferedReader

0

I made a program that reads a txt file line by line with a BufferedReader. If the line that reads finds the String "Issue Date", it takes from character 83 to 93 of that line (which would be the actual date) and saves it in a String variable to then apply a particular format.

Problem to solve:

The "Issue Date" comes with format (EXAMPLE) --- > 12/6/2018

I need the format to be ALWAYS of type 06/12/2018 (that is DD / MM / YYYY).

What I came up with was this:

   while ((strLine = br.readLine()) != null)   {
                    if(strLine.contains("Fecha de Emision: ")){
                        String date = strLine.substring(83,93);
                        SimpleDateFormat format = new SimpleDateFormat("MM/dd/YYYY");
                        String dateString = format.format(new Date(date));
                        String newDate = strLine.replace(date, dateString);
                        writer.write(newDate+"\n");
                    }
                    else{
                        writer.write(strLine+"\n");
                    }
                }

It does work if the date comes in the format 6/12/2018, but I add a 0 (zero) random average in case the date comes right, I mean in 06/12/2018 format , what would be wrong for the functionality I need.

I can not think of how I can validate the format and then tell the program, if the format is: 6/12/2018 change it and if so 06/12/2018 leave it as it is.

Help, advice? Thank you very much!

    
asked by Nacho Zve De La Torre 18.10.2018 в 15:26
source

1 answer

1

What you can do is a String#split() with the date bar (/) .
And there:

  • Verify that you have an array of length 3 (day, month, and year).
  • Convert the three values of the array to int without throwing a NumberFormatException (do it inside a try - catch ).
  • And reassemble the String by concatenating the 3 values, taking into account that if the day or month is less than 9 you have to add a '0' in front of the respective value (when you rearm the string).
  • Note: I did not put it, but you can also validate the maximum and minimum for each field, mainly day and month.

        
    answered by 18.10.2018 / 15:47
    source