Java examples for java.util:Calendar Calculation
floor Calendar
//package com.java2s; import java.util.Calendar; public class Main { public static void main(String[] argv) throws Exception { Calendar calendar = Calendar.getInstance(); int field = 2; floor(calendar, field);/*from w w w .j av a 2s . c o m*/ } public static void floor(Calendar calendar, int field) { floor(calendar, field, 1); } public static void floor(Calendar calendar, int field, int number) { switch (field) { case Calendar.YEAR: yearFloor(calendar); break; case Calendar.MONTH: monthFloor(calendar, number); break; case Calendar.WEEK_OF_YEAR: weekFloor(calendar); break; case Calendar.DAY_OF_WEEK: dayFloor(calendar); break; case Calendar.DAY_OF_MONTH: dayFloor(calendar); break; case Calendar.HOUR_OF_DAY: hourFloor(calendar, number); break; case Calendar.MINUTE: minuteFloor(calendar, number); break; case Calendar.SECOND: secondFloor(calendar); break; } } public static void yearFloor(Calendar calendar) { monthFloor(calendar); calendar.set(Calendar.MONTH, 0); } public static void monthFloor(Calendar calendar) { dayFloor(calendar); calendar.set(Calendar.DAY_OF_MONTH, 1); } public static void monthFloor(Calendar calendar, int number) { //number param for quarter and half dayFloor(calendar); calendar.set(Calendar.DAY_OF_MONTH, 1); if (number > 1) { int month = calendar.get(Calendar.MONTH); calendar.set(Calendar.MONTH, (month / number) * number); } } public static void weekFloor(Calendar calendar) { int i = calendar.get(Calendar.YEAR); int k = calendar.get(Calendar.DAY_OF_YEAR); int l = calendar.get(Calendar.DAY_OF_WEEK); int i1 = calendar.getFirstDayOfWeek(); int j1 = l - i1; if (j1 > 0) { k -= j1; } else if (j1 < 0) { k -= 7 + j1; } calendar.clear(); boolean flag = calendar.isLenient(); if (!flag) { calendar.setLenient(true); } calendar.set(Calendar.YEAR, i); calendar.set(Calendar.DAY_OF_YEAR, k); if (!flag) { int j = calendar.get(Calendar.YEAR); calendar.setLenient(false); } } public static void dayFloor(Calendar calendar) { hourFloor(calendar); calendar.set(Calendar.HOUR_OF_DAY, 0); } public static void hourFloor(Calendar calendar) { minuteFloor(calendar); calendar.set(Calendar.MINUTE, 0); } public static void hourFloor(Calendar calendar, int number) { minuteFloor(calendar); calendar.set(Calendar.MINUTE, 0); if (number > 1) { int hours = calendar.get(Calendar.HOUR); calendar.set(Calendar.HOUR, (hours / number) * number); } } public static void minuteFloor(Calendar calendar) { secondFloor(calendar); calendar.set(Calendar.SECOND, 0); } public static void minuteFloor(Calendar calendar, int number) { secondFloor(calendar); calendar.set(Calendar.SECOND, 0); if (number > 1) { int minutes = calendar.get(Calendar.SECOND); calendar.set(Calendar.SECOND, (minutes / number) * number); } } public static void secondFloor(Calendar calendar) { calendar.set(Calendar.MILLISECOND, 0); } }