[Android][工具類]TimeUtils

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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * 日期時間格式封裝 工具類
 *
 */
public class TimeUtils {
    public static final String TIME_FORMAT_STYLE_DIANDIAN = "yyyy.MM.dd";
    public static final String TIME_FORMAT_STYLE_YMD = "yyyy/MM/dd HH:mm";
    public static final String Time_FORMAT_YEAD = "yyyy年MM月dd日 HH:mm";
    public static final String Time_POSITION = "yyyy/MM/dd";
    public static final String TIME_FORMAT_STYLE_MD = "MM月dd日 HH:mm";
    private final static Pattern emailer = Pattern
            .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
    // private final static SimpleDateFormat dateFormater = new
    // SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // private final static SimpleDateFormat dateFormater2 = new
    // SimpleDateFormat("yyyy-MM-dd");

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

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

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

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

    /**
     * 將字符串轉(zhuǎn)為日期類型
     *
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate) {
        Date d = new Date();
        d.setTime(Long.parseLong(sdate) * 1000);
        return d;
    }

    /**
     * 友好方式顯示日期
     *
     * @param sdate
     * @return
     */
    public static String friendly_time(String sdate) {
        Date time = toDate(sdate);
        Log.i("toDate", time.toString());
        return friendly_time1(time);
    }

    /**
     * 以友好的方式顯示時間
     *
     * @param time
     * @return
     */
    public static String friendly_time1(Date time) {

        if (time == null) {
            return "Unknown";
        }

        Date serviceTime = new Date();
        if (serviceTime == null) {
            return "Unknown1";
        }
        String ftime = "";

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

        long lt = time.getTime() / 86400000;
        long ct = serviceTime.getTime() / 86400000;
        int days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((serviceTime.getTime() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max(
                        (serviceTime.getTime() - 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 - 1) + "天前";
        } else if (days > 10) {
            ftime = dateFormater2.get().format(time);
        }
        return ftime;
    }

    /**
     * 判斷給定字符串時間是否為今日
     *
     * @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 isThisMonth(String sdate) {
        boolean b = false;
        Date time = toDate(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = dateFormater3.get().format(today);
            String timeDate = dateFormater3.get().format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 判斷是否為今年婚脱,必須固定格式如下 :2014-01-01
     *
     * @param time 如:2014-01-01
     * @return
     */
    public static boolean isThisYear(String time) {
        if (time.length() != 10) {
            return false;
        } else {
            Date today = new Date();
            String nowDate = dateFormater2.get().format(today);
            if (nowDate.substring(0, 4).equals(time.substring(0, 4))) {
                return true;
            } else {
                return false;
            }
        }

    }

    /**
     * 判斷給定字符串是否空白串铅乡。 空白串是指由空格望伦、制表符听系、回車符、換行符組成的字符串 若輸入字符串為null或空字符串,返回true
     *
     * @param input
     * @return boolean
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input))
            return true;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }


    /**
     * 格式化顯示時間
     * @param dateStr  yyyy-MM-dd HH:mm:ss
     * @return
     */
//    public static String formatDate(String dateStr) {
//
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        Date date;
//        try {
//            date = sdf.parse(dateStr);
//        } catch (ParseException e) {
//            date = new Date();
//            e.printStackTrace();
//        }
//        String needStr = sdf.format(date);
//        return needStr;
//    }

    /**
     * @param dateStr
     * @param format
     * @return
     */
    public static Date parseDate(String dateStr, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            date = new Date();
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 格式化時間
     *
     * @param time
     * @param format
     * @return
     */
    public static String formatTime(long time, String format) {
        if (time == 0 || TextUtils.isEmpty(format)) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format.toString());
        Date date = new Date(time);
        String dateStr = sdf.format(date);
        return dateStr;
    }

    /**
     * 格式化時間
     *
     * @return
     */
    public static String formatTime(String strTime) {
        long time = Long.parseLong(strTime);
        if (time == 0 || TextUtils.isEmpty(TIME_FORMAT_STYLE_YMD)) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT_STYLE_YMD.toString());
        Date date = new Date(time * 1000);
        String dateStr = sdf.format(date);
        return dateStr;
    }

    /**
     * 格式化時間
     *
     * @return
     */
    public static String formatTime(String strTime, String format) {
        long time = Long.parseLong(strTime);
        if (time == 0 || TextUtils.isEmpty(format)) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format.toString());
        Date date = new Date(time * 1000);
        String dateStr = sdf.format(date);
        return dateStr;
    }


    /*時間戳轉(zhuǎn)換成字符竄*/
    static SimpleDateFormat sf;

    public static String getDateToString(long time) {
        Date d = new Date(time);
        sf = new SimpleDateFormat("yyyy年MM月dd日");
        return sf.format(d);
    }

    public static String formatTimeMonth(String strTime) {
        long time = Long.parseLong(strTime);
        if (time == 0 || TextUtils.isEmpty(TIME_FORMAT_STYLE_MD)) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT_STYLE_MD.toString());
        Date date = new Date(time * 1000);
        String dateStr = sdf.format(date);
        return dateStr;
    }

    /**
     * 根據(jù)年 月 獲取對應(yīng)的月份 天數(shù)
     */
    public static int getDaysByYearMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.DATE, 1);
        cal.roll(Calendar.DATE, -1);
        int maxDate = cal.get(Calendar.DATE);
        return maxDate;
    }

    /**
     * 將字符串轉(zhuǎn)為日期類型
     *
     * @param sdate
     * @return
     */
    public static Date toDate2(String sdate) {

        try {
            if (sdate.contains("/")) {
                return dateFormater2.get().parse(sdate);
            } else {
                return dateFormater4.get().parse(sdate);
            }
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 獲取當(dāng)前年月日
     *
     * @return
     */
    public static String getCurrentTime() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateNowStr = sdf.format(d);
        return dateNowStr;
    }

    /**
     * 獲取當(dāng)前年月日
     *
     * @return
     */
    public static long getCurrentLongTime() {
        return System.currentTimeMillis() / 1000;
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子巍糯,更是在濱河造成了極大的恐慌,老刑警劉巖值纱,帶你破解...
    沈念sama閱讀 218,204評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異虐唠,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評論 3 395
  • 文/潘曉璐 我一進店門搓幌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人迅箩,你說我怎么就攤上這事溉愁∷乔鳎” “怎么了拐揭?”我有些...
    開封第一講書人閱讀 164,548評論 0 354
  • 文/不壞的土叔 我叫張陵奕塑,是天一觀的道長堂污。 經(jīng)常有香客問我,道長龄砰,這世上最難降的妖魔是什么盟猖? 我笑而不...
    開封第一講書人閱讀 58,657評論 1 293
  • 正文 為了忘掉前任换棚,我火速辦了婚禮,結(jié)果婚禮上娘汞,老公的妹妹穿的比我還像新娘夕玩。我一直安慰自己价说,他們只是感情好风秤,可當(dāng)我...
    茶點故事閱讀 67,689評論 6 392
  • 文/花漫 我一把揭開白布扮叨。 她就那樣靜靜地躺著,像睡著了一般碍沐。 火紅的嫁衣襯著肌膚如雪衷蜓。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,554評論 1 305
  • 那天磁浇,我揣著相機與錄音,去河邊找鬼无虚。 笑死,一個胖子當(dāng)著我的面吹牛友题,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播踢匣,決...
    沈念sama閱讀 40,302評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼戈抄,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了呛凶?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,216評論 0 276
  • 序言:老撾萬榮一對情侶失蹤模闲,失蹤者是張志新(化名)和其女友劉穎崭捍,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體殷蛇,經(jīng)...
    沈念sama閱讀 45,661評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡粒梦,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,851評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了匀们。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,977評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡重抖,死狀恐怖祖灰,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情局扶,我是刑警寧澤叁扫,帶...
    沈念sama閱讀 35,697評論 5 347
  • 正文 年R本政府宣布陌兑,位于F島的核電站,受9級特大地震影響兔综,放射性物質(zhì)發(fā)生泄漏狞玛。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,306評論 3 330
  • 文/蒙蒙 一心肪、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧慧瘤,春花似錦固该、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽每瞒。三九已至,卻和暖如春剿骨,著一層夾襖步出監(jiān)牢的瞬間埠褪,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評論 1 270
  • 我被黑心中介騙來泰國打工组橄, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留罚随,地道東北人。 一個月前我還...
    沈念sama閱讀 48,138評論 3 370
  • 正文 我出身青樓遵班,卻偏偏與公主長得像,于是被迫代替她去往敵國和親狭郑。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,927評論 2 355

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