Home > Software design >  Why can't I generate local date from int values in Java [closed]
Why can't I generate local date from int values in Java [closed]

Time:09-16

I wanted the program to take input of date as a string and remove delimiters and whitespace from it then transfer the values to String[] and then change it to int[] and then store the values in variables and then with those variables make a local date . But I don't know why this throws an error .

Code:

import java.util.Scanner;
import java.time.format.*;
import java.time.*;

public class Main {
  public static void main(String[] args) {
    Scanner darshit = new Scanner(System.in);
    String oo = "";
    System.out.println("Enter your DOB: ");
    String dobb = darshit.next();
    String dob = dobb.replaceAll("\\s", "");
    String[] Dob = dob.split("[\\s\\-\\.\\'\\?\\,\\_\\@] ");
 int[] words = new int[Dob.length];
      for (int i = 0; i < Dob.length; i  )

      {
        words[i] = Integer.parseInt(Dob[i]);
      }
      int birthday_d = words[0];
      int birthday_m = words[1]-1;
      int birthday_y = words[2];
      System.out.println(birthday_d);
      System.out.println(birthday_m);
      System.out.println(birthday_y);
      LocalDate today = LocalDate.now();
      LocalDate birthday = LocalDate.of(birthday_d, birthday_m, birthday_y);
   System.out.println(birthday);
}
}

Error:

Enter your DOB: 
25-06-2008
25
5
2008
Exception in thread "main" java.time.DateTimeException: Invalid value for DayOfMonth (valid values 1 - 28/31): 2008
    at java.base/java.time.temporal.ValueRange.checkValidValue(ValueRange.java:311)
    at java.base/java.time.temporal.ChronoField.checkValidValue(ChronoField.java:717)
    at java.base/java.time.LocalDate.of(LocalDate.java:270)
    at Main.main(source.java:31)
Process finished with exit code 1.

I am a beginner , so any type of help will be appreciated by bottom of heart!

CodePudding user response:

This was because the LocalDate.of() take parameters as yyyy-MM-dd not dd-MM-yyyy . So if you input 25-06-2008 The local date takes the input as 2008-06-25 so the dd value 2008 isn't possible because it allows values 1-28/31.

Define a DateTimeFormatter to fit your expected input.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-yyyy" ) ;

Use that formatted when parsing the input.

LocalDate dateOfBirth = LocalDate.parse( input , f ) ;

CodePudding user response:

I added a print statement to your code that shows the problem more clearly:

public static void main (String[] args) throws InterruptedException
{
    try (Scanner darshit = new Scanner (System.in))
    {
        System.out.println ("Enter your DOB: ");
        String dobb = darshit.next ();
        String dob = dobb.replaceAll ("\\s", "");
        String[] Dob = dob.split ("[\\s\\-\\.\\'\\?\\,\\_\\@] ");
        int[] words = new int[Dob.length];
        for (int i = 0; i < Dob.length; i  )
        {
            System.out.printf ("Dob[%d]: %s %n%n%n", i, Dob[i]);
            Thread.sleep (100); // Allow time for output to show up
            words[i] = Integer.parseInt (Dob[i]);
        }
        int birthday_d = words[0];
        int birthday_m = words[1] - 1;
        int birthday_y = words[2];
        System.out.println (birthday_d);
        System.out.println (birthday_m);
        System.out.println (birthday_y);
        LocalDate birthday = LocalDate.of (birthday_d, birthday_m, birthday_y);
        System.out.println (birthday);
    }
}

Using the DateFormat utility class leads to a simpler solution. This isn't complete, but shows the core method.

public static void main (String[] args) throws ParseException
{
    DateFormat df = DateFormat.getDateInstance (DateFormat.SHORT);
    String sample = "9/14/2021";
    Date date = df.parse (sample);
    System.out.printf ("%s as Date: %s %n", sample, date);
}
  • Related