Returns a field of the current time as an integer. - Android java.util

Android examples for java.util:Time

Description

Returns a field of the current time as an integer.

Demo Code


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";
    /**/*  w w w.  ja v a2 s. co  m*/
     * Returns a field of the current time 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
     * @return the desired field
     */
    public static int getCurrentTimeField(int field) {
        //Get calendar for current time
        Calendar now = Calendar.getInstance();
        //Select appropriate field
        switch (field) {
        case MINUTE_OF_DAY:
            return (now.get(Calendar.HOUR_OF_DAY) * MINUTES_PER_HOUR)
                    + now.get(Calendar.MINUTE);
        case MINUTE_OF_HOUR:
            return now.get(Calendar.MINUTE);
        case HOUR_OF_DAY:
            return now.get(Calendar.HOUR_OF_DAY);
        case DAY_OF_YEAR:
            return now.get(Calendar.DAY_OF_YEAR);
        default:
            Log.e(TAG, ERR_MESSAGE_INVALID_FIELD
                    + "(in getCurrentTimeField())");
            return -1;
        }
    }
}

Related Tutorials