Search code examples
javadatedeprecated

How do I replace the deprecated method Date.setHours(int)?


I have some deprecated Date methods in my Java code and I would appreciate if someone can guide me here please. I have a private Date variable:

private Date startime;
private Date endTime;

and in my method I have declared:

Calendar calender = Calendar.getInstance();
this.startTime = calender.getTime();
this.startTime.setHours(0); // ----> is depreacted

this.endTime.setHours(startTime.getHours()); // -->deprecated line as well

Other methods such as setMinutes() and getMinutes() are also deprecated.

I know that I have to use Calendar.set(Calendar.HOUR_OF_DAY, hour). How can use the new code here? all the setHours, getMinutes, etc are all over-lined.

        if (query.getCount() > 0 && query.moveToFirst()) {
          Calendar calender = Calendar.getInstance();
          this.startTime = calender.getTime();
          this.startTime.setHours(0);
          this.startTime.setMinutes(query.getInt("startTimeOfDayMins"));

          this.daysOfWeek = (query.getString("daysOfWeek")).toLowerCase();

          this.endTime = calender.getTime();
          this.endTime.setHours(startTime.getHours());
          this.endTime.setMinutes(startTime.getMinutes() + query.getInt("durationMins"));

        this.context = null;
    }

Solution

  • If I understand your question correctly, this should work:

    int hours = 0;
    Calendar calendar = Calendar.getInstance();
    calendar.set( Calendar.HOUR_OF_DAY, hours );
    this.startTime = calendar.getTime();
    
    this.endTime = calendar.getTime();
    

    If not, can you show us the full method where you want to replace the date code?

    EDIT: Here is the updated version for your full method. Basically how it works is that once you get an instance of the Calendar object it maintains its state. Since you are not planning on changing the hours it only has to be set once. Since you are updating the minutes from your query you will have to set it again before calling calendar.getTime().

        if (query.getCount() > 0 && query.moveToFirst())
        {
            int hours = 0;
            int minutes = query.getInt( "startTimeOfDayMins" );
    
            Calendar calendar = Calendar.getInstance();
            calendar.set( Calendar.HOUR, hours );
            calendar.set( Calendar.MINUTE, minutes );
            this.startTime = calendar.getTime();
    
            this.daysOfWeek = ( query.getString( "daysOfWeek" ) ).toLowerCase();
    
            calendar.set( Calendar.MINUTE, minutes + query.getInt( "durationMins" ) );
            this.endTime = calendar.getTime();
    
            this.context = null;
        }