I’m pretty new to java. My objective is to let a user input a date in “dd/MM/yyyy” format and for me to be able to add these dates to a calendar array list and then display the array with all the dates in it.
ArrayList<Calendar> dob = new ArrayList<Calendar>();
Calendar dobs = Calendar.getInstance();
//traveller dobs
for (int count = 0; count < tAmount; count++)
{
System.out.println("---Please write the dates in the following format dd/mm/yyyy--- ");
System.out.println("Write dates in same order as names!- ");
System.out.println("Day such as '09':");
day = keyboard.nextInt();
System.out.println("Month such as '11':");
month = keyboard.nextInt();
System.out.println("Year such as '1998':");
year = keyboard.nextInt();
//format & add to arraylist
dobs.set(year, month, day);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.format(dobs);
dob.add(dobs);
};
System.out.println(id +"n"+ name+"n" + tAmount+"n" + travellers+"n" +dob+"n" + dateCreated);
I tried searching for answers here and elsewhere but I could not find what I was looking for and the threads I did look into just confused me further. Here is the output I get when I run this code:
If I remove the date format stuff I get this:
…
What I’m looking for is something like: [20-10-1999,12-03-1998,…]
I’m not really understanding how to properly use calendar and would appreciate any help.
Advertisement
Answer
tl;dr
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
List < LocalDate > dates =
List
.of( "23/01/2021" , "17/02/2021" )
.stream()
.map(
( String s ) -> LocalDate.parse( s , formatter )
)
.toList();
System.out.println( "dates = " + dates );
[2021-01-23, 2021-02-17]
Details
Never use Date
and SimpleDateFormat
classes. These were years ago supplanted by the modern java.time classes defined in JSR 310.
List < String > inputs = List.of( "23/01/2021", "17/02/2021" ) ;
List< LocalDate > dates = new ArrayList<>( inputs.size() ) ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
for( String input : inputs )
{
LocalDate date = LocalDate.parse( input , f ) ;
dates.add( date ) ;
}
If you have the year, month, and day components as separate numbers, use another factory method.
LocalDate.of( y , m , d )
To display the LocalDate
objects, let java.time automatically localize.
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( locale) ;
for( LocalDate date : dates )
{
String output = date.format( f ) ;
…
}
Or you can write another custom format as seen in first code snippet, using DateTimeFormatter.ofPattern
.