RootAtKali
RootAtKali

Reputation: 185

how to ceil and floor a Calendar Date by 10 minnutes?

there is a better way to round (ceil and floor) a date-time by ten minutes of the following code:

public void hintOfTime() {
        Date orario = new SimpleDateFormat("hh:mm").parse(usaServizio_standard.setStr());
        // I have skipped the try catch for an easy read
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(orario);
        int minutes = calendar.get(Calendar.MINUTE);
        if(minutes>=1 && minutes<=9) {
            usaServizio_standard.hint("not valid date","Try with: "+ calendar.get(Calendar.HOUR+1)+":00 or "+calendar.get(Calendar.HOUR+1)+":10");
        }else if(minutes>=11 && minutes<=19) {
            usaServizio_standard.hint("not valid date","Try with: "+ calendar.get(Calendar.HOUR+1)+":10 or "+calendar.get(Calendar.HOUR+1)+":20");
        }else if(minutes>=21 && minutes<=29) {
            usaServizio_standard.hint("not valid date","Try with: "+ calendar.get(Calendar.HOUR+1)+":20 or "+calendar.get(Calendar.HOUR+1)+":30");
        }else if(minutes>=31 && minutes<=39) {
            usaServizio_standard.consiglio("not valid date","Try with: "+ calendar.get(Calendar.HOUR+1)+":30 or "+calendar.get(Calendar.HOUR+1)+":40");
        }else if(minutes>=41 && minutes<=49) {
            usaServizio_standard.consiglio("not valid date","Try with "+ calendar.get(Calendar.HOUR+1)+":40 or "+calendar.get(Calendar.HOUR+1)+":50");
        }else {
            usaServizio_standard.hint("not valid date","Try with"+ calendar.get(Calendar.HOUR+1)+":50 or "+calendar.get(Calendar.HOUR+2)+":00");
        }
    }

this solution works fine but is so ugly. I don't know if there is a better and short solution for doing the same works.

Upvotes: 1

Views: 613

Answers (1)

Anonymous
Anonymous

Reputation: 86323

java.time

I recommend that you use java.time, the modern Java date and time API, for your time work.

    String timeString = "09:56";
    
    LocalTime time = LocalTime.parse(timeString);
    int minute = time.getMinute();
    if (minute % 10 != 0) {
        // truncate to whole 10 minutes
        LocalTime firstSuggestedTime = time.withMinute(minute / 10 * 10);
        LocalTime secondSuggestedTime = firstSuggestedTime.plusMinutes(10);
        System.out.format("Not a valid time; try with %s or %s.%n",
                firstSuggestedTime, secondSuggestedTime);
    }

Output from this example was:

Not a valid time; try with 09:50 or 10:00.

Link

Oracle tutorial: Date Time explaining how to use java.time.

Upvotes: 7

Related Questions