Android examples for java.util:Date Convert
Returns a field of a Calendar as an integer.
import android.util.Log; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class Main{ private static final String TAG = TimeUtils.class.getName(); /**Minutes elapsed in current day**/ public static final int MINUTE_OF_DAY = 1; /**Minutes elapsed in current hour**/ public static final int MINUTE_OF_HOUR = 2; /**Hours elapsed in current day (24 hour format)**/ public static final int HOUR_OF_DAY = 4; /**Days elapsed in current year**/ public static final int DAY_OF_YEAR = 8; /** Minute precision **/ public static final int MINUTE = 32; public static final int MINUTES_PER_HOUR = 60; private static final String ERR_MESSAGE_INVALID_FIELD = "Invalid time field requested"; /**/*from w w w. j a va 2s. c o m*/ * Returns a field of a Calendar as an integer. Fields accepted: MINUTE_OF_DAY, MINUTE_OF_HOUR, HOUR_OF_DAY, * DAY_OF_YEAR * * @param field The field to retrieve * @param cal the Calendar * @return the desired field */ public static int getTimeField(Calendar cal, int field) { //Select appropriate field switch (field) { case MINUTE_OF_DAY: return (cal.get(Calendar.HOUR_OF_DAY) * MINUTES_PER_HOUR) + cal.get(Calendar.MINUTE); case MINUTE_OF_HOUR: return cal.get(Calendar.MINUTE); case HOUR_OF_DAY: return cal.get(Calendar.HOUR_OF_DAY); case DAY_OF_YEAR: return cal.get(Calendar.DAY_OF_YEAR); default: Log.e(TAG, ERR_MESSAGE_INVALID_FIELD + "(in getCurrentTimeField())"); return -1; } } /** * Returns a field of a Date as an integer. Fields accepted: MINUTE_OF_DAY, MINUTE_OF_HOUR, HOUR_OF_DAY, * DAY_OF_YEAR * * @param field The field (i.e. minute, hour, etc) to retrieve * @param date the Date * @return the desired field */ public static int getTimeField(Date date, int field) { return getTimeField(dateToCalendar(date), field); } /** * Converts a Date to a Calendar * * @param date date to convert * @return a calendar */ public static Calendar dateToCalendar(Date date) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(date.getTime()); cal.setTimeZone(TimeZone.getDefault()); return cal; } }