I'm trying to use Scanner method to let me input a date of birth in this format - mm/dd/yy and the output that I'd like to get would be something like this.
Input - 02/06/12
Output - February 6, 2012
I'm also trying to limit the value for day(dd) and make sure it doesn't go past 32, and the value for year(yy) to not exceed 2022. I assume I save the input as a String, however I'm not sure how to separate them and have a condition where I can assign certain String values to each month.
CodePudding user response:
Following is the working code to your above problem statement as given below. Please add logic for date accordingly as I am assuming that you will be submitting the date in YYYY
format.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Date:");
String date = scanner.nextLine(); // Read user input
System.out.println("Submitted Date is: " date); // Output user input
String arr[] = date.split("/");
System.out.println("Output --> " getMonth(arr[0]) " " getDate(arr[1]) ", " arr[2]);
}
public static String getMonth(String month) {
if (Integer.parseInt(month) > 12) {
throw new IllegalArgumentException("Invalid Month");
}
switch (month) {
case "01":
return "January";
case "02":
return "February";
case "03":
return "March";
case "04":
return "April";
case "05":
return "May";
case "06":
return "June";
case "07":
return "July";
case "08":
return "August";
case "09":
return "September";
case "10":
return "October";
case "11":
return "November";
case "12":
return "December";
default:
return "Invalid Month";
}
}
public static String getDate(String date) {
if (date.startsWith("0")) {
return String.valueOf(date.charAt(1));
}
if (Integer.parseInt(date) > 31) {
throw new IllegalArgumentException("Invalid Date");
}
return date;
}
CodePudding user response:
Parse as a LocalDate
object. Automatically localize to generate output text.
LocalDate
.parse(
"02/06/12" ,
DateTimeFormatter.ofPattern( "MM/dd/uu" )
)
.format(
DateTimeFormatter
.ofLocalizedDate( FormatStyle.MEDIUM )
.withLocale( Locale.US )
)
To handle faulty input, trap for DateTimeParseException
.
To constrain the year, interrogate for the year using LocalDate#getYear
. Or, build a custom Jakarta Bean Validation validator.
All of this has been covered many times already on Stack Overflow. So search to learn more.