Android 倒計時CountDownTimer

image.png

美工妹子給的圖如下,訂單在創(chuàng)建時間的24小時后進行關(guān)閉

業(yè)務邏輯

從后臺返回來的訂單創(chuàng)建時間加24小時后減去你當下的時間
就是相差的總共時間,然后進行倒計時
倒計時結(jié)束后上傳訂單關(guān)閉標識,改變狀態(tài)頁

實現(xiàn)思路

可能在沒有遇到CountDownTimer之前,我們都是創(chuàng)建Handle來開啟異步線程來處理,如果你現(xiàn)在使用,我只能說太菜了,官方已經(jīng)為我們封裝好了一個類,爽的很,一起來看

 @Override
    public void initData() {
        countDownTimer = new CountDownTimer(time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (!TestActivity.this.isFinishing()) {

                    long day = millisUntilFinished / (1000 * 24 * 60 * 60); //單位天

                    long hour = (millisUntilFinished - day * (1000 * 24 * 60 * 60)) / (1000 * 60 * 60);
                    //單位時
                    long minute = (millisUntilFinished - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60)) / (1000 * 60);
                    //單位分
                    long second = (millisUntilFinished - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000;
                    //單位秒
                    textView.setText(hour + "小時" + minute + "分鐘" + second + "秒");
                }
            }

            /**
             *倒計時結(jié)束后調(diào)用的
             */
            @Override
            public void onFinish() {

            }

        };
        countDownTimer.start();
    }

傳了兩個參數(shù),第一個參數(shù)就是時間的總值,換算成毫秒值,第二個代表以毫秒來計算

兩個方法:
onTick :倒計時執(zhí)行的方法
onFinsh:倒計時結(jié)束后的方法
countDownTimer.start(); 開始倒計時

就是這么簡單,但是兩個坑,來看下

  • 空指針問題

在某些場景下婆芦,CountDownTimer 會導致空指針 如果在Activity或者Fragment被回收時并未調(diào)用CountDownTimer的cancel()方法結(jié)束自己唇跨,這個時候CountDownTimer的Handler方法中如果判斷到當前的時間未走完因俐,那么會繼續(xù)調(diào)用onTick方法耸弄,Activity或者Fragment已經(jīng)被系統(tǒng)回收句惯,從而里面的變量被設置為Null,同時卓练,CountDownTimer中的Handler方法還在繼續(xù)執(zhí)行叮喳,這一塊空間始終無法被系統(tǒng)回收也就造成了內(nèi)存泄漏。
*在CountDownTimer的onTick方法中記得對當前對象做判空處理
*#####可能造成內(nèi)存泄漏問題

 * 記得關(guān)閉,負責內(nèi)存溢出
 */
@Override
protected void onDestroy() {
    super.onDestroy();
    if (countDownTimer != null) {
        countDownTimer.cancel();
        countDownTimer = null;
    }
}

干貨推薦,項目中關(guān)于時間處理的Util,這篇全了

/*
 * 
 */
package com.wisdom.patient.utils;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.util.Log;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

/**
 * 描述:日期處理類.
 *
 */
@SuppressWarnings("all")
public class TimeUtil {
    /**
     * one day millisecond count
     */
    public static final long ONE_DAY_MILLISECONDS = 1000 * 3600 * 24;

    public static final long ONE_HOUR_MILLISECONDS = 1000 * 3600;

    public static final long ONE_MIN_MILLISECONDS = 1000 * 60;

    /**
     * 時間日期格式化到年月日時分秒.
     */
    public static String dateFormatYMDHMS = "yyyy-MM-dd HH:mm:ss";
    public static String dateFormatYMDHMS_f = "yyyyMMddHHmmss";
    public static String dateFormatMDHM = "MM-dd HH:mm";
    public static String dateFormat = "yyyy-MM-dd HH:mm";
    /**
     * 時間日期格式化到年月日.
     */
    public static String dateFormatYMD = "yyyy-MM-dd";

    /**
     * 時間日期格式化到年月日時分.中文顯示
     */
    public static String dateFormatYMDHMofChinese = "yyyy年MM月dd日 HH:mm";

    /**
     * 時間日期格式化到年月日.中文顯示
     */
    public static String dateFormatYMDofChinese = "yyyy年MM月dd日";
    /**
     * 時間日期格式化到月日.中文顯示
     */
    public static String dateFormatMDofChinese = "MM月dd日";
    /**
     * 時間日期格式化到月.中文顯示
     */
    public static String dateFormatMofChinese = "MM月";
    /**
     * 時間日期格式化到年月.
     */
    public static String dateFormatYM = "yyyy-MM";

    /**
     * 時間日期格式化到年月日時分.
     */
    public static String dateFormatYMDHM = "yyyy-MM-dd HH:mm";

    /**
     * 時間日期格式化到月日.
     */
    public static String dateFormatMD = "MM/dd";
    public static String dateFormatM_D = "MM-dd";

    public static String dateFormatM = "MM月";
    public static String dateFormatD = "dd";
    public static String dateFormatM2 = "MM";

    public static String dateFormatMDHMofChinese = "MM月dd日HH時mm分";
    public static String dateFormatHMofChinese = "HH時mm分";

    /**
     * 時分秒.
     */
    public static String dateFormatHMS = "HH:mm:ss";

    /**
     * 時分.
     */
    public static String dateFormatHM = "HH:mm";

    /**
     * 上午/下午時分
     */
    public static String dateFormatAHM = "aHH:mm";

    public static String dateFormatYMDE = "yyyy/MM/dd E";
    public static String dateFormatYMD2 = "yyyy/MM/dd";

    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @SuppressLint("SimpleDateFormat")
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    @SuppressLint("SimpleDateFormat")
    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };

    /**
     * 時間戳轉(zhuǎn)特定格式時間
     * @param dataFormat
     * @param timeStamp
     * @return
     */
    public static String formatData(String dataFormat, long timeStamp) {
        if (timeStamp == 0) {
            return "";
        }
        timeStamp = timeStamp * 1000;
        SimpleDateFormat format = new SimpleDateFormat(dataFormat);
        return format.format(new Date(timeStamp));
    }

    /**
     * 將毫秒轉(zhuǎn)換成秒
     *
     * @param time
     * @return
     */
    public static int convertToSecond(Long time) {
        Date date = new Date();
        date.setTime(time);
        return date.getSeconds();
    }

    /**
     * 描述:String類型的日期時間轉(zhuǎn)化為Date類型.
     *
     * @param strDate String形式的日期時間
     * @param format  格式化字符串巨柒,如:"yyyy-MM-dd HH:mm:ss"
     * @return Date Date類型日期時間
     */
    public static Date getDateByFormat(String strDate, String format) {
        SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = mSimpleDateFormat.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 描述:獲取偏移之后的Date.
     *
     * @param date          日期時間
     * @param calendarField Calendar屬性樱拴,對應offset的值, 如(Calendar.DATE,表示+offset天,Calendar.HOUR_OF_DAY,表示+offset小時)
     * @param offset        偏移(值大于0,表示+,值小于0,表示-)
     * @return Date 偏移之后的日期時間
     */
    public Date getDateByOffset(Date date, int calendarField, int offset) {
        Calendar c = new GregorianCalendar();
        try {
            c.setTime(date);
            c.add(calendarField, offset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return c.getTime();
    }

    /**
     * 描述:獲取指定日期時間的字符串(可偏移).
     *
     * @param strDate       String形式的日期時間
     * @param format        格式化字符串洋满,如:"yyyy-MM-dd HH:mm:ss"
     * @param calendarField Calendar屬性晶乔,對應offset的值, 如(Calendar.DATE,表示+offset天,Calendar.HOUR_OF_DAY,表示+offset小時)
     * @param offset        偏移(值大于0,表示+,值小于0,表示-)
     * @return String String類型的日期時間
     */
    public static String getStringByOffset(String strDate, String format, int calendarField, int offset) {
        String mDateTime = null;
        try {
            Calendar c = new GregorianCalendar();
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            c.setTime(mSimpleDateFormat.parse(strDate));
            c.add(calendarField, offset);
            mDateTime = mSimpleDateFormat.format(c.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return mDateTime;
    }

    /**
     * 描述:Date類型轉(zhuǎn)化為String類型(可偏移).
     *
     * @param date          the date
     * @param format        the format
     * @param calendarField the calendar field
     * @param offset        the offset
     * @return String String類型日期時間
     */
    public static String getStringByOffset(Date date, String format, int calendarField, int offset) {
        String strDate = null;
        try {
            Calendar c = new GregorianCalendar();
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            c.setTime(date);
            c.add(calendarField, offset);
            strDate = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strDate;
    }

    /**
     * from yyyy-MM-dd HH:mm:ss to MM-dd HH:mm
     */
    public static String formatDate(String before) {
        String after;
        try {
            Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
                    .parse(before);
            after = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault()).format(date);
        } catch (ParseException e) {
            return before;
        }
        return after;
    }

    /**
     * 描述:Date類型轉(zhuǎn)化為String類型.
     *
     * @param date   the date
     * @param format the format
     * @return String String類型日期時間
     */
    public static String getStringByFormat(Date date, String format) {
        SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
        String strDate = null;
        try {
            strDate = mSimpleDateFormat.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strDate;
    }

    /**
     * 描述:獲取指定日期時間的字符串,用于導出想要的格式.
     *
     * @param strDate String形式的日期時間牺勾,必須為yyyy-MM-dd HH:mm:ss格式
     * @param format  輸出格式化字符串正罢,如:"yyyy-MM-dd HH:mm:ss"
     * @return String 轉(zhuǎn)換后的String類型的日期時間
     */
    public static String getStringByFormat(String strDate, String format) {
        String mDateTime = null;
        try {
            Calendar c = new GregorianCalendar();
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            c.setTime(mSimpleDateFormat.parse(strDate));
            SimpleDateFormat mSimpleDateFormat2 = new SimpleDateFormat(format);
            mDateTime = mSimpleDateFormat2.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mDateTime;
    }

    /**
     * 描述:獲取milliseconds表示的日期時間的字符串.
     *
     * @param format 格式化字符串,如:"yyyy-MM-dd HH:mm:ss"
     * @return String 日期時間字符串
     */
    public static String getStringByFormat(long milliseconds, String format) {
        String thisDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            thisDateTime = mSimpleDateFormat.format(milliseconds);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return thisDateTime;
    }

    /**
     * 描述:獲取表示當前日期時間的字符串.
     *
     * @param format 格式化字符串驻民,如:"yyyy-MM-dd HH:mm:ss"
     * @return String String類型的當前日期時間
     */
    public static String getCurrentDate(String format) {
        String curDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            Calendar c = new GregorianCalendar();
            curDateTime = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;

    }


    //獲取當前系統(tǒng)當天日期
    public static String getCurrentDay() {
        String curDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(dateFormat);
            Calendar c = new GregorianCalendar();
            c.add(Calendar.DAY_OF_MONTH, 0);
            curDateTime = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }

    //獲取當前系統(tǒng)當天日期
    public static String getCurrentDay2() {
        String curDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(dateFormatYMDHMS);
            Calendar c = new GregorianCalendar();
            c.add(Calendar.DAY_OF_MONTH, 0);
            curDateTime = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }

    //獲取當前系統(tǒng)前后第幾天
    public static String getNextDay(int i) {
        String curDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(dateFormat);
            Calendar c = new GregorianCalendar();
            c.add(Calendar.DAY_OF_MONTH, i);
            curDateTime = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }
    //獲取當前系統(tǒng)前后第幾小時
    public static String getNextHour(int i) {
        String curDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(dateFormat);
            Calendar c = new GregorianCalendar();
            c.add(Calendar.HOUR_OF_DAY, i);
            curDateTime = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }

    /**
     * 描述:獲取表示當前日期時間的字符串(可偏移).
     *
     * @param format        格式化字符串翻具,如:"yyyy-MM-dd HH:mm:ss"
     * @param calendarField Calendar屬性,對應offset的值回还, 如(Calendar.DATE,表示+offset天,Calendar.HOUR_OF_DAY,表示+offset小時)
     * @param offset        偏移(值大于0,表示+,值小于0,表示-)
     * @return String String類型的日期時間
     */
    public static String getCurrentDateByOffset(String format, int calendarField, int offset) {
        String mDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            Calendar c = new GregorianCalendar();
            c.add(calendarField, offset);
            mDateTime = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mDateTime;

    }

    /**
     * 描述:計算兩個日期所差的天數(shù).
     *
     * @param date1 第一個時間的毫秒表示
     * @param date2 第二個時間的毫秒表示
     * @return int 所差的天數(shù)
     */
    public static int getOffectDay(long date1, long date2) {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTimeInMillis(date1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTimeInMillis(date2);
        //先判斷是否同年
        int y1 = calendar1.get(Calendar.YEAR);
        int y2 = calendar2.get(Calendar.YEAR);
        int d1 = calendar1.get(Calendar.DAY_OF_YEAR);
        int d2 = calendar2.get(Calendar.DAY_OF_YEAR);
        int maxDays = 0;
        int day = 0;
        if (y1 - y2 > 0) {
            maxDays = calendar2.getActualMaximum(Calendar.DAY_OF_YEAR);
            day = d1 - d2 + maxDays;
        } else if (y1 - y2 < 0) {
            maxDays = calendar1.getActualMaximum(Calendar.DAY_OF_YEAR);
            day = d1 - d2 - maxDays;
        } else {
            day = d1 - d2;
        }
        return day;
    }

    /**
     * 描述:計算兩個日期所差的小時數(shù).
     *
     * @param date1 第一個時間的毫秒表示
     * @param date2 第二個時間的毫秒表示
     * @return int 所差的小時數(shù)
     */
    public static int getOffectHour(long date1, long date2) {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTimeInMillis(date1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTimeInMillis(date2);
        int h1 = calendar1.get(Calendar.HOUR_OF_DAY);
        int h2 = calendar2.get(Calendar.HOUR_OF_DAY);
        int h = 0;
        int day = getOffectDay(date1, date2);
        h = h1 - h2 + day * 24;
        return h;
    }

    /**
     * 描述:計算兩個日期所差的分鐘數(shù).
     *
     * @param date1 第一個時間的毫秒表示
     * @param date2 第二個時間的毫秒表示
     * @return int 所差的分鐘數(shù)
     */
    public static int getOffectMinutes(long date1, long date2) {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTimeInMillis(date1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTimeInMillis(date2);
        int m1 = calendar1.get(Calendar.MINUTE);
        int m2 = calendar2.get(Calendar.MINUTE);
        int h = getOffectHour(date1, date2);
        int m = 0;
        m = m1 - m2 + h * 60;
        return m;
    }

    /**
     * 描述:獲取本周一.
     *
     * @param format the format
     * @return String String類型日期時間
     */
    public static String getFirstDayOfWeek(String format) {
        return getDayOfWeek(format, Calendar.MONDAY);
    }

    /**
     * 描述:獲取本周日.
     *
     * @param format the format
     * @return String String類型日期時間
     */
    public static String getLastDayOfWeek(String format) {
        return getDayOfWeek(format, Calendar.SUNDAY);
    }

    /**
     * 描述:獲取本周的某一天.
     *
     * @param format        the format
     * @param calendarField the calendar field
     * @return String String類型日期時間
     */
    private static String getDayOfWeek(String format, int calendarField) {
        String strDate = null;
        try {
            Calendar c = new GregorianCalendar();
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            int week = c.get(Calendar.DAY_OF_WEEK);
            if (week == calendarField) {
                strDate = mSimpleDateFormat.format(c.getTime());
            } else {
                int offectDay = calendarField - week;
                if (calendarField == Calendar.SUNDAY) {
                    offectDay = 7 - Math.abs(offectDay);
                }
                c.add(Calendar.DATE, offectDay);
                strDate = mSimpleDateFormat.format(c.getTime());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strDate;
    }

    /**
     * 描述:獲取本月第一天.
     *
     * @param format the format
     * @return String String類型日期時間
     */
    public static String getFirstDayOfMonth(String format) {
        String strDate = null;
        try {
            Calendar c = new GregorianCalendar();
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            //當前月的第一天
            c.set(GregorianCalendar.DAY_OF_MONTH, 1);
            strDate = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strDate;
    }

    /**
     * 描述:獲取本月最后一天.
     *
     * @param format the format
     * @return String String類型日期時間
     */
    public static String getLastDayOfMonth(String format) {
        String strDate = null;
        try {
            Calendar c = new GregorianCalendar();
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            // 當前月的最后一天
            c.set(Calendar.DATE, 1);
            c.roll(Calendar.DATE, -1);
            strDate = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strDate;
    }


    /**
     * 描述:獲取表示當前日期的0點時間毫秒數(shù).
     *
     * @return the first time of day
     */
    public static long getFirstTimeOfDay() {
        Date date = null;
        try {
            String currentDate = getCurrentDate(dateFormatYMD);
            date = getDateByFormat(currentDate + " 00:00:00", dateFormatYMDHMS);
            return date.getTime();
        } catch (Exception e) {
        }
        return -1;
    }

    /**
     * 描述:獲取表示當前日期24點時間毫秒數(shù).
     *
     * @return the last time of day
     */
    public static long getLastTimeOfDay() {
        Date date = null;
        try {
            String currentDate = getCurrentDate(dateFormatYMD);
            date = getDateByFormat(currentDate + " 24:00:00", dateFormatYMDHMS);
            return date.getTime();
        } catch (Exception e) {
        }
        return -1;
    }

    /**
     * 描述:判斷是否是閏年()
     * <p>(year能被4整除 并且 不能被100整除) 或者 year能被400整除,則該年為閏年.
     *
     * @param year 年代(如2012)
     * @return boolean 是否為閏年
     */
    public static boolean isLeapYear(int year) {
        if ((year % 4 == 0 && year % 400 != 0) || year % 400 == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 描述:根據(jù)時間返回幾天前或幾分鐘的描述.
     *
     * @param strDate the str date
     * @return the string
     */
    public static String formatDateStr2Desc(String strDate, String outFormat) {

        DateFormat df = new SimpleDateFormat(dateFormatYMDHM);
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c2.setTime(df.parse(strDate));
            c1.setTime(new Date());
            int d = getOffectDay(c1.getTimeInMillis(), c2.getTimeInMillis());
            if (d == 0) {
                int h = getOffectHour(c1.getTimeInMillis(), c2.getTimeInMillis());
                if (h > 0) {
                    return h + "小時前";
                } else if (h < 0) {
                    return Math.abs(h) + "小時后";
                } else if (h == 0) {
                    int m = getOffectMinutes(c1.getTimeInMillis(), c2.getTimeInMillis());
                    if (m > 0) {
                        return m + "分鐘前";
                    } else if (m < 0) {
                        return Math.abs(m) + "分鐘后";
                    } else {
                        return "剛剛";
                    }
                }
            } else if (d > 0) {
                if (d == 1) {
                    return "昨天";
                } else if (d == 2) {
                    return "前天";
                }
            } else if (d < 0) {
                if (d == -1) {
                    return "明天";
                } else if (d == -2) {
                    return "后天";
                }
                return Math.abs(d) + "天后";
            }

            String out = getStringByFormat(strDate, outFormat);
            if (!TextUtils.isEmpty(out)) {
                return out;
            }
        } catch (Exception e) {
        }

        return strDate;
    }


    /**
     * 取指定日期為星期幾
     *
     * @param strDate  指定日期
     * @param inFormat 指定日期格式
     * @return String   星期幾
     */
    public static String getWeekNumber(String strDate, String inFormat) {
        String week = "星期日";
        Calendar calendar = new GregorianCalendar();
        DateFormat df = new SimpleDateFormat(inFormat);
        try {
            calendar.setTime(df.parse(strDate));
        } catch (Exception e) {
            return "錯誤";
        }
        int intTemp = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        switch (intTemp) {
            case 0:
                week = "星期日";
                break;
            case 1:
                week = "星期一";
                break;
            case 2:
                week = "星期二";
                break;
            case 3:
                week = "星期三";
                break;
            case 4:
                week = "星期四";
                break;
            case 5:
                week = "星期五";
                break;
            case 6:
                week = "星期六";
                break;
        }
        return week;
    }

    /**
     * 將字符串轉(zhuǎn)位日期類型
     *
     * @param sdate
     * @return
     */
    private static Date toDate(String sdate) {
        try {
            return dateFormater.get().parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 以友好的方式顯示時間
     *
     * @param ms
     * @return
     */
    public static String getfriendlyTime(Long ms) {
        if (ms == null) return "";
//      Date time = toDate(sdate);
        Date time = new Date();
        time.setTime(ms);

        if (time == null) {
            return "Unknown";
        }
        String ftime = "";
        Calendar cal = Calendar.getInstance();

        // 判斷是否是同一天
        String curDate = dateFormater2.get().format(cal.getTime());
        String paramDate = dateFormater2.get().format(time);
        if (curDate.equals(paramDate)) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0) {
                if (((cal.getTimeInMillis() - time.getTime()) / 60000) < 1) {
                    ftime = "剛剛";
                } else {
                    ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分鐘前";
                }
            } else {
                ftime = hour + "小時前";
            }
            return ftime;
        }

        long lt = time.getTime() / 86400000;
        long ct = cal.getTimeInMillis() / 86400000;
        int days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max(
                        (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                        + "分鐘前";
            else
                ftime = hour + "小時前";
        } else if (days == 1) {
            ftime = "昨天";
        } else if (days == 2) {
            ftime = "前天";
        } else if (days > 2 && days <= 10) {
            ftime = days + "天前";
        } else if (days > 10) {
            ftime = dateFormater2.get().format(time);
        }
        return ftime;
    }

    /**
     * 距離當前多少個小時
     *
     * @param dateStr
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static int getExpiredHour(String dateStr) {
        int ret = -1;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date;
        try {
            date = sdf.parse(dateStr);
            Date dateNow = new Date();

            long times = date.getTime() - dateNow.getTime();
            if (times > 0) {
                ret = ((int) (times / ONE_HOUR_MILLISECONDS));
            } else {
                ret = -1;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return ret;
    }

    /**
     * 過了多少個小時
     * @param dateStr
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static int getExpiredHour2(String dateStr) {
        int ret = -1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date sendDate;
        try {
            sendDate = sdf.parse(dateStr);
            Date dateNow = new Date(System.currentTimeMillis());
            Log.e("JPush","date="+sendDate);
            long times = dateNow.getTime() - sendDate.getTime();
            Log.e("JPush","date.getTime()="+sendDate.getTime());
            if (times > 0) {
                ret = ((int) (times / ONE_HOUR_MILLISECONDS));
                int sdqf =(int)Math.floor(times /ONE_HOUR_MILLISECONDS);
            } else {
                ret = -1;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Log.e("JPush","ret="+ret);
        return ret;
    }


    /**
     * 判斷給定字符串時間是否為今日
     *
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate) {
        boolean b = false;
        Date time = toDate(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = dateFormater2.get().format(today);
            String timeDate = dateFormater2.get().format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 判斷給定字符串時間是否為今日
     *
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(long sdate) {
        boolean b = false;
        Date time = new Date(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = dateFormater2.get().format(today);
            String timeDate = dateFormater2.get().format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 根據(jù)用戶生日計算年齡
     */
    public static int getAgeByBirthday(Date birthday) {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthday)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }

        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

        cal.setTime(birthday);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                // monthNow==monthBirth
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                // monthNow>monthBirth
                age--;
            }
        }
        return age;
    }

    /**
     * 友好顯示時間差
     *
     * @param diff 毫秒
     * @return
     */
    public static String getFriendTimeOffer(long diff) {
        int day = (int) (diff / (24 * 60 * 60 * 1000));
        if (day > 0)
            return day + "天";
        int time = (int) (diff / (60 * 60 * 1000));
        if (time > 0)
            return time + "小時";
        int min = (int) (diff / (60 * 1000));
        if (min > 0)
            return min + "分鐘";
        int sec = (int) diff / 1000;
        if (sec > 0)
            return sec + "秒";
        return "1秒";
    }

    /**
     * 友好的時間間隔
     *
     * @param duration 秒
     * @return
     */
    public static String getFriendlyDuration(long duration) {
        String str = "";
        long tmpDuration = duration;
        str += (tmpDuration / 60 > 10 ? tmpDuration / 60 : "0" + tmpDuration / 60) + ":";
        tmpDuration %= 60;
        str += (tmpDuration / 1 >= 10 ? tmpDuration / 1 : "0" + tmpDuration / 1);
        tmpDuration %= 1;
        return str;
    }
    /**
     * 友好的時間間隔2
     *
     * @param duration 秒
     * @return
     */
    public static String getFriendlyDuration2(long duration) {
        String str = "";
        long tmpDuration = duration;
        str += (tmpDuration / 60>0?tmpDuration / 60+"'":"");
        tmpDuration %= 60;
        str += (tmpDuration / 1>=10?tmpDuration / 1+"''":"0"+tmpDuration / 1+"''");
        tmpDuration %= 1;
        return str;
    }

    public static String getFriendlyMusicDuration(long duration) {
        String str = "-";
        int tmpDuration = (int) (duration / 1000);//秒
        str += (tmpDuration / 3600 > 10 ? tmpDuration / 3600 : "0" + tmpDuration / 3600) + ":";
        tmpDuration %= 3600;
        str += (tmpDuration / 60 > 10 ? tmpDuration / 60 : "0" + tmpDuration / 60) + ":";
        tmpDuration %= 60;
        str += (tmpDuration / 1 >= 10 ? tmpDuration / 1 : "0" + tmpDuration / 1);
        tmpDuration %= 1;
        return str;
    }

    /**
     * 通過日期來確定星座
     *
     * @param mouth
     * @param day
     * @return
     */
    public static String getStarSeat(int mouth, int day) {
        String starSeat = null;
        if ((mouth == 3 && day >= 21) || (mouth == 4 && day <= 19)) {
            starSeat = "白羊座";
        } else if ((mouth == 4 && day >= 20) || (mouth == 5 && day <= 20)) {
            starSeat = "金牛座";
        } else if ((mouth == 5 && day >= 21) || (mouth == 6 && day <= 21)) {
            starSeat = "雙子座";
        } else if ((mouth == 6 && day >= 22) || (mouth == 7 && day <= 22)) {
            starSeat = "巨蟹座";
        } else if ((mouth == 7 && day >= 23) || (mouth == 8 && day <= 22)) {
            starSeat = "獅子座";
        } else if ((mouth == 8 && day >= 23) || (mouth == 9 && day <= 22)) {
            starSeat = "處女座";
        } else if ((mouth == 9 && day >= 23) || (mouth == 10 && day <= 23)) {
            starSeat = "天秤座";
        } else if ((mouth == 10 && day >= 24) || (mouth == 11 && day <= 22)) {
            starSeat = "天蝎座";
        } else if ((mouth == 11 && day >= 23) || (mouth == 12 && day <= 21)) {
            starSeat = "射手座";
        } else if ((mouth == 12 && day >= 22) || (mouth == 1 && day <= 19)) {
            starSeat = "摩羯座";
        } else if ((mouth == 1 && day >= 20) || (mouth == 2 && day <= 18)) {
            starSeat = "水瓶座";
        } else {
            starSeat = "雙魚座";
        }
        return starSeat;
    }

    /**
     * 返回聊天時間
     * @return
     */
    public static  String getChatTimeForShow(long time){
        if(TimeUtil.isToday(time)){
            return TimeUtil.getStringByFormat(time, TimeUtil.dateFormatHMofChinese);
        }else{
            return TimeUtil.getStringByFormat(time, TimeUtil.dateFormatMDHMofChinese);
        }
    }

    /**
     * 獲取指定時間的毫秒值
     */
    public static long getDatelongMills(String fomat,String dateStr){
        SimpleDateFormat sdf = new SimpleDateFormat(fomat);
        Date date = null;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long longDate = date.getTime();
        return longDate;
    }

    /**
     * 兩個日期比較
     * @param DATE1
     * @param DATE2
     * @return
     */
    public static int compare_date(String DATE1, String DATE2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() - dt2.getTime()>0) {//date1>date2
                return 1;
            } else {
                return -1;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }
    /**
     *
     * 給時間加幾個小時
     */


    public static String addDateMinut(String day, int hour){

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = null;

        try {

            date = format.parse(day);

        } catch (Exception ex) {

            ex.printStackTrace();

        }

        if (date == null)

            return "";

        System.out.println("front:" + format.format(date)); //顯示輸入的日期

        Calendar cal = Calendar.getInstance();

        cal.setTime(date);

        cal.add(Calendar.HOUR, hour);// 24小時制

        date = cal.getTime();

        System.out.println("after:" + format.format(date));  //顯示更新后的日期

        cal = null;

        return format.format(date);



    }

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末裆泳,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子柠硕,更是在濱河造成了極大的恐慌工禾,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,183評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件仅叫,死亡現(xiàn)場離奇詭異帜篇,居然都是意外死亡糙捺,警方通過查閱死者的電腦和手機诫咱,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來洪灯,“玉大人坎缭,你說我怎么就攤上這事竟痰。” “怎么了掏呼?”我有些...
    開封第一講書人閱讀 168,766評論 0 361
  • 文/不壞的土叔 我叫張陵坏快,是天一觀的道長。 經(jīng)常有香客問我憎夷,道長莽鸿,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,854評論 1 299
  • 正文 為了忘掉前任拾给,我火速辦了婚禮祥得,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蒋得。我一直安慰自己级及,他們只是感情好,可當我...
    茶點故事閱讀 68,871評論 6 398
  • 文/花漫 我一把揭開白布额衙。 她就那樣靜靜地躺著饮焦,像睡著了一般。 火紅的嫁衣襯著肌膚如雪窍侧。 梳的紋絲不亂的頭發(fā)上县踢,一...
    開封第一講書人閱讀 52,457評論 1 311
  • 那天,我揣著相機與錄音伟件,去河邊找鬼殿雪。 笑死,一個胖子當著我的面吹牛锋爪,可吹牛的內(nèi)容都是我干的丙曙。 我是一名探鬼主播,決...
    沈念sama閱讀 40,999評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼其骄,長吁一口氣:“原來是場噩夢啊……” “哼亏镰!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起拯爽,我...
    開封第一講書人閱讀 39,914評論 0 277
  • 序言:老撾萬榮一對情侶失蹤索抓,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后毯炮,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體逼肯,經(jīng)...
    沈念sama閱讀 46,465評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,543評論 3 342
  • 正文 我和宋清朗相戀三年桃煎,在試婚紗的時候發(fā)現(xiàn)自己被綠了篮幢。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,675評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡为迈,死狀恐怖三椿,靈堂內(nèi)的尸體忽然破棺而出缺菌,到底是詐尸還是另有隱情,我是刑警寧澤搜锰,帶...
    沈念sama閱讀 36,354評論 5 351
  • 正文 年R本政府宣布伴郁,位于F島的核電站,受9級特大地震影響蛋叼,放射性物質(zhì)發(fā)生泄漏焊傅。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,029評論 3 335
  • 文/蒙蒙 一狈涮、第九天 我趴在偏房一處隱蔽的房頂上張望租冠。 院中可真熱鬧,春花似錦薯嗤、人聲如沸顽爹。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽镜粤。三九已至,卻和暖如春玻褪,著一層夾襖步出監(jiān)牢的瞬間肉渴,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評論 1 274
  • 我被黑心中介騙來泰國打工带射, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留同规,地道東北人。 一個月前我還...
    沈念sama閱讀 49,091評論 3 378
  • 正文 我出身青樓窟社,卻偏偏與公主長得像券勺,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子灿里,可洞房花燭夜當晚...
    茶點故事閱讀 45,685評論 2 360

推薦閱讀更多精彩內(nèi)容