Returns a field of the current time as a floating point number. - Android java.util

Android examples for java.util:Time

Description

Returns a field of the current time as a floating point number.

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();
    /**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;
    public static final int HOURS_PER_DAY = 24;
    private static final String ERR_MESSAGE_INVALID_FIELD = "Invalid time field requested";
    /**//from   w w w  . j a  v a  2  s .co  m
     * Returns a field of the current time as a floating point number. Fields accepted: HOUR_OF_DAY, DAY_OF_YEAR.
     *
     * @param field The field (i.e. minute, hour, etc) to retrieve
     * @return the desired field
     */
    public static double getCurrentTimeFieldFractional(int field) {
        //Get calendar for current time
        Calendar now = Calendar.getInstance();
        //Select appropriate field
        switch (field) {
        case HOUR_OF_DAY:
            return now.get(Calendar.HOUR_OF_DAY)
                    + (now.get(Calendar.MINUTE) / (double) MINUTES_PER_HOUR);
        case DAY_OF_YEAR:
            return now.get(Calendar.DAY_OF_YEAR)
                    + (now.get(Calendar.HOUR_OF_DAY) / (float) HOURS_PER_DAY);
        default:
            Log.e(TAG, ERR_MESSAGE_INVALID_FIELD
                    + "(in getCurrentTimeFieldFractional())");
            return -1;
        }
    }
}

Related Tutorials