javastringdatedate-formatdateformatter

Get the Month from a date string


I have a String input of date "10/10/2020" (assume they are always going to be separated with /) and I am trying to store each category in a private int variable already defined as Month, Day, and year.

I used the parseInt, indexOf, and substring methods to find the month and store it in the month variable but I am having a hard time figuring out how I can have the program read the day. We are to assume that the month and day can be in "00" or "0" formats.

This is how I am reading the month from the string and this is what I got so far for reading the day but I am getting an error.

java.lang.StringIndexOutOfBoundsException: begin 2, end 0, length 8

This is my code so far please let me know what mistake I am doing.

    int firstSlash = date.indexOf("/");
    int secondSlash = date.indexOf("/", firstSlash);
    
    month = Integer.parseInt (date.substring (0, firstSlash));
    day = Integer.parseInt (date.substring(firstSlash+1, secondSlash-1));
    

I don't want the answer but please help me understand the logic of where I am going wrong because based on my understanding I seem to be getting the Index values between the first and second slash and converting the String value into an int.


Solution

  • Your code should be like

    String date = "10/10/2020";
    int firstSlash = date.indexOf("/");
    int secondSlash = date.indexOf("/", firstSlash + 1);
    
    int month = Integer.parseInt (date.substring (0, firstSlash));
    int day = Integer.parseInt (date.substring(firstSlash+1, secondSlash));
    

    It's better to use LocalDate to store date and use DateTimeFormatter to parse the date.