Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 日期時間工具類 TimestampTool 完整整理

編輯:關於 Android 程式設計

專案裡日期處理幾乎無處不在:列表顯示「今天/昨天」、計算年齡、兩個日期相差幾天、取得本週一、格式化時間字串……與其每個模組各寫一遍,不如收攏成一個工具類。以下這份 TimestampTool 涵蓋了毫秒轉時間、格式化、日期偏移、週次計算、年齡推算等常見需求,可直接取用。

主要能力一覽

* 毫秒與 Timestamp 互轉、取得當前時間字串
* 只取日期或取到秒的兩種精度
* 格式化字串與 Date 雙向轉換(yyyy-MM-dd、yyyy-MM-dd HH:mm:ss)
* 取得前/後 N 天的日期、N 個月前的日期、N 年前的年份
* 取得指定日期之後(或之前)的某一天,含閏年處理
* 判斷某日期串是「今天」、「昨天」還是實際日期
* 取得本週一、上/下週一,以及某週的完整七天
* 比較兩個日期的先後、計算相差天數與相差年數
* 依生日推算年齡

完整程式碼

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class TimestampTool {

    /** 將毫秒轉成時間 */
    public static String getTimeMillisToDate(long l) {
        Timestamp d = new Timestamp(l);
        return d.toString().substring(0, 19);
    }

    /** 當前時間 */
    public static Timestamp crunttime() {
        return new Timestamp(System.currentTimeMillis());
    }

    /** 當前時間字串,只到日期,例如 2006-07-07 */
    public static String getCurrentDate() {
        Timestamp d = crunttime();
        return d.toString().substring(0, 10);
    }

    /** 當前時間字串,例如 2006-07-07 22:10:10 */
    public static String getCurrentDateTime() {
        Timestamp d = crunttime();
        return d.toString().substring(0, 19);
    }

    /** 星期幾 */
    public static String getWeekDay() {
        Calendar date = Calendar.getInstance();
        date.setTime(crunttime());
        return new SimpleDateFormat("EEEE").format(date.getTime());
    }

    /** 指定時間的字串,只到日期 */
    public static String getStrDate(Timestamp t) {
        return t.toString().substring(0, 10);
    }

    /** 指定時間的字串,取到秒 */
    public static String getStrDateTime(Timestamp t) {
        return t.toString().substring(0, 19);
    }

    /** 獲得當前日期往前推 N 天的日期字串 */
    public static String getStrIntervalDate(String days) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -Integer.parseInt(days));
        return sdf.format(cal.getTime());
    }

    /** 字串轉時間:yyyy-MM-dd HH:mm:ss -> Date */
    public static Date parseDateTime(String dt) {
        Date jDt = new Date();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (dt.length() > 10) {
                jDt = sdf.parse(dt);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return jDt;
    }

    /** Date 轉字串:Date -> yyyy-MM-dd HH:mm:ss */
    public static String parseDateTime(Date date) {
        String s = null;
        if (date != null) {
            try {
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                s = f.format(date);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return s;
    }

    /** 字串轉日期:yyyy-MM-dd -> Date */
    public static Date parseDate(String dt) {
        Date jDt = new Date();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (dt.length() >= 8) {
                jDt = sdf.parse(dt);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return jDt;
    }

    /** Date 轉字串:Date -> yyyy-MM-dd */
    public static String parseDate(Date date) {
        String s = null;
        try {
            if (date != null) {
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
                s = f.format(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

    /** 補齊短日期,變成 yyyy-MM-dd 00:00:00 */
    public static String getLongDateFromShortDate(String dt) {
        String strDT = dt;
        try {
            if (strDT != null && strDT.length() <= 10) {
                strDT = dt.trim() + " 00:00:00";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return strDT;
    }

    /** 補齊短日期,變成 yyyy-MM-dd HH:mm */
    public static String getShortDateToHHMM(String dt) {
        String jDt = dt;
        try {
            if (jDt != null && jDt.length() <= 10) {
                jDt = jDt + " 00:00";
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            jDt = sdf.parse(jDt).toLocaleString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return jDt;
    }

    /** 正規化到 HH:mm 精度 */
    public static String formatDateToHHMM(String dateStr) {
        String resultDate = null;
        try {
            if (dateStr.length() > 10) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Date date = sdf.parse(dateStr);
                resultDate = sdf.format(date);
            } else {
                resultDate = dateStr;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return resultDate;
    }

    /** 日期字串轉 Timestamp,格式 2006-07-05 */
    public static Timestamp date(String str) {
        Timestamp tp = null;
        if (str.length() <= 10) {
            String[] string = str.trim().split("-");
            int one = Integer.parseInt(string[0]) - 1900;
            int two = Integer.parseInt(string[1]) - 1;
            int three = Integer.parseInt(string[2]);
            tp = new Timestamp(one, two, three, 0, 0, 0, 0);
        }
        return tp;
    }

    /** 取得指定日期之後(day 為負則往前)的日期字串 */
    public static String getNextDay(String strDate, int day) {
        if (strDate != null && !strDate.equals("")) {
            Calendar cal1 = Calendar.getInstance();
            String[] string = strDate.trim().split("-");
            int one = Integer.parseInt(string[0]) - 1900;
            int two = Integer.parseInt(string[1]) - 1;
            int three = Integer.parseInt(string[2]);
            cal1.setTime(new Date(one, two, three));
            cal1.add(Calendar.DAY_OF_MONTH, day);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            return formatter.format(cal1.getTime());
        } else {
            return null;
        }
    }

    /** 取得指定日期 N 年之後的日期字串,閏年 2 月 29 日也能正確處理 */
    public static String getNextYear(String strDate, int year) {
        Calendar cal1 = Calendar.getInstance();
        String[] string = strDate.trim().split("-");
        int one = Integer.parseInt(string[0]) - 1900;
        int two = Integer.parseInt(string[1]) - 1;
        int three = Integer.parseInt(string[2]);
        cal1.setTime(new Date(one, two, three));
        cal1.add(Calendar.YEAR, year);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(cal1.getTime());
    }

    /** 日期加時間轉 Timestamp,格式 2006-07-05 22:10:10 */
    public static Timestamp datetime(String str) {
        Timestamp tp = null;
        if (str != null && str.length() > 10) {
            String[] string = str.trim().split(" ");
            String[] date = string[0].split("-");
            String[] time = string[1].split(":");
            int date1 = Integer.parseInt(date[0]) - 1900;
            int date2 = Integer.parseInt(date[1]) - 1;
            int date3 = Integer.parseInt(date[2]);
            int time1 = Integer.parseInt(time[0]);
            int time2 = Integer.parseInt(time[1]);
            int time3 = Integer.parseInt(time[2]);
            tp = new Timestamp(date1, date2, date3, time1, time2, time3, 0);
        }
        return tp;
    }

    /** 日期加時間(不含秒)轉 Timestamp,格式 2006-07-05 22:10 */
    public static Timestamp datetimeHm(String str) {
        Timestamp tp = null;
        if (str.length() > 10) {
            String[] string = str.trim().split(" ");
            String[] date = string[0].split("-");
            String[] time = string[1].split(":");
            int date1 = Integer.parseInt(date[0]) - 1900;
            int date2 = Integer.parseInt(date[1]) - 1;
            int date3 = Integer.parseInt(date[2]);
            int time1 = Integer.parseInt(time[0]);
            int time2 = Integer.parseInt(time[1]);
            tp = new Timestamp(date1, date2, date3, time1, time2, 0, 0);
        }
        return tp;
    }

    /** 獲得當前日期與本週一相差的天數 */
    private static int getMondayPlus() {
        Calendar calendar = Calendar.getInstance();
        // 注意 Calendar 中週日是第一天、週一是第二天
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        return (dayOfWeek == 1) ? -6 : 2 - dayOfWeek;
    }

    /**
     * 獲得相對當前週的某一週的週一
     * @param week 0 表示本週,-1 上週,1 下週
     */
    public static Date getMondayOfWeek(int week) {
        int mondayPlus = getMondayPlus();
        GregorianCalendar current = new GregorianCalendar();
        current.add(GregorianCalendar.DATE, mondayPlus + 7 * week);
        return current.getTime();
    }

    /** 獲得某日往前或往後 N 天的日期 */
    public static Date getDay(Date date, int day) {
        GregorianCalendar c = new GregorianCalendar();
        c.setTime(date);
        c.add(GregorianCalendar.DATE, day);
        return c.getTime();
    }

    /** 獲得某一週七天(含週一)的日期字串陣列 */
    public static String[] getDaysOfWeek(int week) {
        String[] days = new String[7];
        Date monday = getMondayOfWeek(week);
        Timestamp t = new Timestamp(monday.getTime());
        days[0] = getStrDate(t);
        for (int i = 1; i < 7; i++) {
            t = new Timestamp(getDay(monday, i).getTime());
            days[i] = getStrDate(t);
        }
        return days;
    }

    /** MCC 的 UTC 時間(秒級)轉 Date */
    public static Date mccUTC2Date(long utc) {
        Date d = new Date();
        d.setTime(utc * 1000);
        return d;
    }

    /** 長時間格式字串轉 Date:yyyy-MM-dd HH:mm:ss */
    public static Date strToDateLong(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        if (strtodate == null) {
            formatter = new SimpleDateFormat("yyyy-MM-dd");
            strtodate = formatter.parse(strDate, pos);
        }
        return strtodate;
    }

    /** yyyy-MM-dd HH:mm 格式字串轉 Date */
    public static Date strToDateTime(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        if (strtodate == null) {
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            strtodate = formatter.parse(strDate, pos);
        }
        return strtodate;
    }

    /** 依輸入字串返回日期部分,格式 2006-07-07 */
    public static String getStrDate(String str) {
        if (str.length() > 10) {
            String[] string = str.trim().split(" ");
            return string[0];
        } else {
            return getCurrentDate();
        }
    }

    /** 當前時間字串,可輸出 2006-07-07_221010 這種適合檔名的形式 */
    public static String getStrDateTime() {
        Timestamp d = crunttime();
        return d.toString().substring(0, 19).replace(":", "").replace(" ", "_");
    }

    /** 依日期字串返回「今天」、「昨天」或原字串 */
    public static String getDayOrDate(String str) {
        if (str != null && !str.equals("")) {
            if (getNextDay(str, 0).equals(getCurrentDate())) {
                str = "今天";
            } else if (getNextDay(str, 1).equals(getCurrentDate())) {
                str = "昨天";
            }
        }
        return str;
    }

    /** 當前日期所在的星期序號,2 對應星期一 */
    public static int getMonOfWeek() {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(new Date());
        return cal1.get(Calendar.DAY_OF_WEEK);
    }

    /** 當前日期往前 N 個月,例如 2007-04-15 前 5 個月為 2006-11-15 */
    public static String getPreviousMonth(int month) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(new Date());
        cal1.add(Calendar.MONTH, -month);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(cal1.getTime());
    }

    /** 取得 N 年前的年份字串 */
    public static String getStrYear(int year) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(new Date());
        cal1.add(Calendar.YEAR, -year);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
        return formatter.format(cal1.getTime()) + "年份";
    }

    /** 比較兩個日期的先後,回傳 endDate 是否晚於 starDate */
    public static boolean compareTwoDays(String starDate, String endDate) {
        Calendar cal_start = Calendar.getInstance();
        Calendar cal_end = Calendar.getInstance();
        cal_start.setTime(parseDate(starDate));
        cal_end.setTime(parseDate(endDate));
        return cal_end.after(cal_start);
    }

    /** 兩個 Calendar 相差的天數,會自動校正先後順序並跨年份累加 */
    public static int getDaysBetween(Calendar d1, Calendar d2) {
        if (d1.after(d2)) {
            Calendar swap = d1;
            d1 = d2;
            d2 = swap;
        }
        int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
        int y2 = d2.get(Calendar.YEAR);
        if (d1.get(Calendar.YEAR) != y2) {
            d1 = (Calendar) d1.clone();
            do {
                days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);
                d1.add(Calendar.YEAR, 1);
            } while (d1.get(Calendar.YEAR) != y2);
        }
        return days;
    }

    /** 兩個日期之間相差的年數 */
    public static int dateDiffYear(String starDate, String endDate) {
        int result = 0;
        Calendar d1 = Calendar.getInstance();
        Calendar d2 = Calendar.getInstance();
        d1.setTime(parseDate(starDate));
        d2.setTime(parseDate(endDate));
        if (d1.after(d2)) {
            Calendar swap = d1;
            d1 = d2;
            d2 = swap;
        }
        int yy = d2.get(Calendar.YEAR) - d1.get(Calendar.YEAR);
        int mm = d2.get(Calendar.MONTH) - d1.get(Calendar.MONTH);
        if (mm < 0) {
            result = yy - 1;
        } else if (mm > 0) {
            result = yy;
        } else {
            result = (d2.getTimeInMillis() - d1.getTimeInMillis()) >= 0 ? yy : yy - 1;
        }
        return result;
    }

    /** 依生日計算年齡 */
    public static int getAgeByBirth(String starDate) {
        return dateDiffYear(starDate, getCurrentDate());
    }
}

使用提醒

這份工具類大量使用 SimpleDateFormat,它並非執行緒安全,若在多執行緒環境共用同一個實例容易出錯,建議每次呼叫時才建立,或改用 ThreadLocal 包裝。另外 new Date(year, month, day) 與 new Timestamp(...) 這類已標記為 deprecated 的建構式,年份需減 1900、月份從 0 起算,維護時要特別留意;新專案更推薦直接採用 java.time(API 26 以上)或 ThreeTenABP 相容庫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved