programmer_new
programmer_new

Reputation: 31

Gregorian Calendar object to match dates inside ArrayList

I am creating a gregorian calendar inside a method called filterBookings() which needs to create a gregorian calendar object inside it to match the dates which are inputted by the user (get selected item from 3 separate ComboBoxes called cmbYear,cmbMonth and cmbDay). The arrayList is called filteredBookings is currently is globally created. If the dates match the index of the matched booking it should be added to the arraylist.The inputs are already mentioned in the code. In the output panel it is saying : Unparseable Date. Can anyone help?I am new to this and do not have a background on this :(

 ArrayList <GregorianCalendar> filteredBookings = new ArrayList<>();
 public PhotoshootManager() throws ParseException {
     initComponents();
     filterBookings();
 }

 public void filterBookings(){   
     GregorianCalendar cal = new GregorianCalendar();

     String getYear =(String) (cmbYear.getSelectedItem());
     String getMonth =(String) (cmbMonth.getSelectedItem());
     String getDay =(String) (cmbDay.getSelectedItem());

     DateFormat setCal = new SimpleDateFormat("dd/MM/yyyy");  
     Calendar cal = Calendar.getInstance();

     try {
         Date date = setCal.parse(getDay+ "/" + getMonth +"/" + getYear);
     } catch (ParseException ex) {

         Logger.getLogger(PhotoshootManager.class.getName()).log(Level.SEVERE, 
                 null, ex);
     }
 }

This is a school project, and unfortunatly we have to use the old GregorianCalendar class.

Upvotes: 0

Views: 387

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 339303

Avoid legacy date-time classes

You are using terrible old date-time classes that were supplanted years ago by the modern java.time classes.

ZonedDateTime

Specifically, the GregorianCalendar class is replaced by ZonedDateTime. This class represents a moment, a point on the timeline, as a date, a time-of-day, and a time zone.

But ZonedDateTime is not appropriate for scheduling future appointments. Instead, we must separate the date and time from the time zone when booking future appointments. More explanation below.

LocalDate

Convert your string inputs for year, month, and day to numbers.

int y = Integer.parseInt( year ) ;
int m = Integer.parseInt( month ) ;
int d = Integer.parseInt( day ) ;

Instantiate a LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.

LocalDate ld = LocalDate.of( y , m , d ) ;

LocalDateTime

Your Booking class should have LocalDateTime member variable. This class purposely lacks any concept of time zone or offset-from-UTC. We use this for future appointments because politicians around the world frequently change the offset of their respective time zone(s). Often, they do so with little or even no warning. For appointments such as “3 PM on January 23” we usually mean 3 PM by the clock on the wall per the time zone currently in force on that date, not as defined today. For example, if the government moves the clock by a half-hour, we do not want our appointment at 2:30, we still want 3:00 — a different moment than if the politicians had left the time zone definitions untouched.

ZoneId

We also need to store the intended time zone with the appointment. The zone is applied to the LocalDateTime at runtime when we need a moment, a specific point on the timeline.

Booking class

So your Booking class looks something like this.

public class Booking {
    String clientName ;
    LocalDateTime appointment ;
    ZoneId zoneId ;
}

To instantiate:

LocalDateTime = LocalDateTime( 2019 , 1 , 23 , 15 , 0 , 0 , 0 ) ; // 3 PM on Jan 23, 2019.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
Booking booking = new Booking( "Alice" , ldt , z ) ;

Collect such instances.

List< Booking > bookings = new ArrayList<>() ;
bookings.add( booking ) ;

Compare to filter

To filter those bookings by a certain date, loop the collected Booking objects, retrieve the LocalDateTime from each, extract the date-only value (a LocalDate), and compare to the target date.

LocalDate target = LocalDate.of( 2019 , Month.FEBRUARY , 1 ) ; // First of February.
List< Booking > filteredBookings = new ArrayList<>() ;
for( Booking booking : bookings ) {
    if( booking.appointment.toLocalDate().isEqual( target ) ) {
        filteredBookings.add( booking ) ; // Collect this `Booking` object whose date matches our target date.
    }
}

ZonedDateTime revisited

When you need a specific moment, such as building a calendar system, or when recording history, apply the time zone (ZoneId) to the date-with-time (LocalDateTime) to get a moment (ZonedDateTime).

ZonedDateTime zdt = booking.appointment.atZone( booking.zone ) ;

To see that moment in UTC, same point on the timeline but a different wall-clock time, extract an Instant object.

Instant instant = zdt.toInstant() ;  // Adjust from time zone to UTC.

Usually best to work with UTC rather than a zoned value for logging, database, storage, and data exchange.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Upvotes: 1

Matteo Tomai
Matteo Tomai

Reputation: 174

Probably one of

 String getYear =(String) (cmbYear.getSelectedItem());
 String getMonth =(String) (cmbMonth.getSelectedItem());
 String getDay =(String) (cmbDay.getSelectedItem());

Is null , also you put an invalid mounth or day java don't go in exception here an example :

        public static void filterBookings(){   
           String getYear ="20192525";
           String getMonth ="4444444444";
           String getDay ="1132632626";



            DateFormat setCal = new SimpleDateFormat("dd/MM/yyyy");  

             try {
                 Date date = setCal.parse(getDay+ "/" + getMonth +"/" + getYear);
                 System.out.println(date);
             } catch (ParseException ex) {

              System.out.println("ko");
             }
           }
    }

output:

Thu Sep 19 00:00:00 CEST 35749996

Upvotes: 0

Level_Up
Level_Up

Reputation: 824

Your error most probably come from this line Date date = setCal.parse(getDay+ "/" + getMonth +"/" + getYear); Here you expect date in format "dd/MM/yyyy" but maybe the values that come as input are different. Please, check what you have for getDay, getMonth and getYear.

P.S. After you find your error you need to make Date obejct to Calendar. You can do this:

 Calendar cal = Calendar.getInstance();
 calendar.setTime(date);
 filteredBookings.add(cal);

Good luck!

Upvotes: 0

Related Questions