Java Time Format getTime(long time, int timeFormat)

Here you can find the source of getTime(long time, int timeFormat)

Description

get Time

License

Apache License

Declaration

public static String getTime(long time, int timeFormat) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static final int HOURS_24_MAKE = 0;

    public static String getTime(long time, int timeFormat) {
        return timeFormat == HOURS_24_MAKE ? getTimeOf24(time) : getTimeOf12(time);
    }//from   w  ww  .ja  va 2s .c  o  m

    private static String getTimeOf24(long time) {
        return getTimeStr(getHourOf24(time), getMinute(time), false);
    }

    private static String getTimeOf12(long time) {
        return getAmPm(time) + " " + getTimeStr(getHourOf12(time), getMinute(time), true);
    }

    private static String getTimeStr(int hour, int minute, boolean is12) {
        StringBuilder temp = new StringBuilder();
        if (is12) {
            temp.append(hour);
        } else {
            temp.append(toTwoDigits(hour));
        }
        temp.append(":");
        temp.append(toTwoDigits(minute));
        return temp.toString();
    }

    private static int getHourOf24(long time) {
        return currentDateTime(time, Calendar.HOUR_OF_DAY);
    }

    private static int getMinute(long time) {
        return currentDateTime(time, Calendar.MINUTE);
    }

    private static String getAmPm(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("aa");
        return sf.format(new Date(time));
        // return getAmPmStr(time) == 0 ? mContext.getString(AM) : mContext.getString(PM);
    }

    private static int getHourOf12(long time) {
        int hour = currentDateTime(time, Calendar.HOUR);
        if (hour == 0)
            hour = 12;
        return hour;
    }

    private static String toTwoDigits(int digit) {
        if (digit >= 10) {
            return "" + digit;
        } else {
            return "0" + digit;
        }
    }

    private static int currentDateTime(long time, int type) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        return calendar.get(type);
    }
}

Related

  1. getTime(@Nonnull String format, @Nonnull String date, @Nonnull String tz)
  2. getTime(Date dt, String format)
  3. getTime(Date time, int format, Locale locale)
  4. getTime(DateFormat df)
  5. getTime(int format)
  6. getTime(String dateStr, String format)
  7. getTime(String dateStr, String formate)
  8. getTime(String format)
  9. getTime(String format, String date)