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

前端 未结 3 1495
情歌与酒
情歌与酒 2021-01-19 00:27

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:

         


        
相关标签:
3条回答
  • 2021-01-19 00:52

    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;
        }
    
    0 讨论(0)
  • 2021-01-19 00:57

    The method setHours for Date is deprecated.

    You can check the documentation here: http://docs.oracle.com/javase/7/docs/api/java/util/Date.html

    If you look at the set hours method you'll see:

    "As of JDK version 1.1, replaced by Calendar.set(Calendar.HOUR_OF_DAY, int hours)."

    0 讨论(0)
  • 2021-01-19 00:58

    You can use Apache Commons Lang3 DateUtils setHours(Date date, int hours)

    0 讨论(0)
提交回复
热议问题