Android时间相关工具类

Android中经常遇到一些时间转换的地方,比如将时间转换成时间戳传给后端,或者从接口获取的是一段时间戳需要转换成时间显示在屏幕上,下面是一些常用的时间转换工具类

import android.text.format.Time;

import com.blankj.utilcode.util.LogUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * 时间格式化工具类                                                       
 */
public class DateUtil {
    private static boolean isInEasternEightZones() {
        return TimeZone.getDefault() == TimeZone.getTimeZone("GMT+08");
    }

    private static boolean isTodayYear(long time) {
        Calendar pre = Calendar.getInstance();
        Date predate = new Date(System.currentTimeMillis());
        pre.setTime(predate);
        Calendar cal = Calendar.getInstance();
        Date date = new Date(time);
        cal.setTime(date);
        return cal.get(Calendar.YEAR) == (pre.get(Calendar.YEAR));
    }

    /**
     * 根据输入的时间和输入的格式获取时间
     *
     * @param time
     * @param timeFormat
     * @return
     */
    public static String getTimeFormatted(long time, String timeFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
        String dateStr = sdf.format(new Date(time * 1000));
        return dateStr;
    }

    private static Date transformTime(Date date, TimeZone oldZone, TimeZone newZone) {
        Date finalDate = null;
        if (date != null) {
            int timeOffset = oldZone.getOffset(date.getTime())
                    - newZone.getOffset(date.getTime());
            finalDate = new Date(date.getTime() - timeOffset);
        }
        return finalDate;
    }

    public static Date formatDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date date = formatter.parse(strDate, pos);
        return date;
    }

    public static Date defaultFormatDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date date = formatter.parse(strDate, pos);
        return date;
    }

    public static String formatString(Date date, int type) {
        DateFormat df = null;
        if (type == 1) {
            df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else {
            df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        }
        return df.format(date);
    }

    public static int compareToday(long when) {
        when = when * 1000;
        Time time = new Time();
        time.set(when);
        int thenYear = time.year;
        int thenMonth = time.month;
        int thenMonthDay = time.monthDay;
        time.set(System.currentTimeMillis());
        if (thenYear < time.year) {
            return -1;
        } else if (thenYear > time.year) {
            return 1;
        } else {
            if (thenMonth < time.month) {
                return -1;
            } else if (thenMonth > time.month) {
                return 1;
            } else {
                if (thenMonthDay < time.monthDay) {
                    if (thenMonthDay == time.monthDay - 1) {
                        //昨天
                        return -2;
                    }
                    return -1;
                } else if (thenMonthDay > time.monthDay) {
                    return 1;
                } else {
                    //今天
                    return 0;
                }
            }
        }
    }

    //年月 xx年xx月
    public static String longToYMC(long time) {
        if (time < 10000000000L) {
            time = time * 1000;
        }
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String timeString = sdf.format(date);//Date-->String
        timeString = timeString.replace("-", "年") + "月";
        return timeString;
    }

    //xx年xx月xx
    public static String longToYMDC(long time) {
        if (time < 10000000000L) {
            time = time * 1000;
        }
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String timeString = sdf.format(date);//Date-->String
        String[] split = timeString.split("-");
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(split[0]);
        stringBuffer.append("年");
        stringBuffer.append(split[1]);
        stringBuffer.append("月");
        stringBuffer.append(split[2]);
        return stringBuffer.toString();
    }

    //年月日时分
    public static String longToYMDHM(long time) {
        if (time < 10000000000L) {
            time = time * 1000;
        }
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String timeString = sdf.format(date);//Date-->String
        return timeString;
    }

    //年月日时分秒
    public static String longToYMDHMS(long time) {
        if (time < 10000000000L) {
            time = time * 1000;
        }
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeString = sdf.format(date);//Date-->String
        return timeString;
    }

    //时分
    public static String longToHM(long time) {
        if (time < 10000000000L) {
            time = time * 1000;
        }
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        String timeString = sdf.format(date);//Date-->String
        return timeString;
    }

    // 秒- 时分
    public static String integerToHM(int time){
        return timeAddZero(time / 3600) + ":" + (time % 3600 /60 == 0 ? "00" : timeAddZero(time % 3600 /60));
    }

    private static String timeAddZero(int time){
        if (time < 10){
            return "0"+time;
        }
        return time+"";
    }

    //时分秒
    public static String longToHMS(long time) {
        if (time < 10000000000L) {
            time = time * 1000;
        }
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String timeString = sdf.format(date);//Date-->String
        return timeString;
    }

    //月日时分
    public static String longToMDHM(long time) {
        if (time < 10000000000L) {
            time = time * 1000;
        }
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
        String timeString = sdf.format(date);//Date-->String
        return timeString;
    }

    //月日时分
    public static String longToMDHMS(long time) {
        if (time < 10000000000L) {
            time = time * 1000;
        }
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
        String timeString = sdf.format(date);//Date-->String
        return timeString;
    }

    public static String longToYMD(long time) {
        if (time < 10000000000L) {
            time = time * 1000;
        }
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String timeString = sdf.format(date);//Date-->String
        return timeString;
    }

    public static String longToMD(long time) {
        if (time < 10000000000L) {
            time = time * 1000;
        }
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd");
        String timeString = sdf.format(date);//Date-->String
        return timeString;
    }

    public static String longToYM(long time) {
        if (time < 10000000000L) {
            time = time * 1000;
        }
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String timeString = sdf.format(date);//Date-->String
        return timeString;
    }

    /**
     * 获取某月的最后一天
     */
    public static long getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //格式化日期
        cal.set(year, month - 1, lastDay, 23, 59, 59);
        Date date = cal.getTime();
        return date.getTime();
    }

    /**
     * 获取某月的最后一天
     */
    public static long getLastDayOfMonth(long time) {
        Date oriDate = new Date(time);
        int month = oriDate.getMonth();
        int year = oriDate.getYear() + 1900;
        Calendar cal = Calendar.getInstance();
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //格式化日期
        cal.set(year, month + 1, 1, 0, 0, 0);
        Date date = cal.getTime();
        return date.getTime();
    }

    /**
     * 获取某月月的第一天
     */
    public static long getFirstDayOfMonth(long time) {
        Date oriDate = new Date(time);
        int month = oriDate.getMonth();
        int year = oriDate.getYear() + 1900;
        Calendar cal = Calendar.getInstance();
        //格式化日期
        cal.set(year, month, 1, 0, 0, 0);
        Date date = cal.getTime();
        return date.getTime();
    }

    public static String longToProgressFormate(long time) {
        StringBuffer stringBuffer = new StringBuffer();
        if (compareToday(time) == 0) {
            stringBuffer.append("今天");
            stringBuffer.append("\n ");
            stringBuffer.append(longToHM(time));
            return stringBuffer.toString();
        } else if (compareToday(time) == -2) {
            stringBuffer.append("昨天");
            stringBuffer.append("\n ");
            stringBuffer.append(longToHM(time));
            return stringBuffer.toString();
        } else {
            String timeString = longToMDHM(time);
            timeString = timeString.replace("-", "月");
            timeString = timeString.replace(" ", "日\n ");
            stringBuffer.append(timeString);
            return stringBuffer.toString();
        }
    }

    public static String formatToYMD(int year, int month, int day) {
        String ymd = year + "-";
        if (month < 10) {
            ymd = ymd + "0" + month;
        } else {
            ymd = ymd + month;
        }
        if (day < 10) {
            ymd = ymd + "-0" + day;
        } else {
            ymd = ymd + "-" + day;
        }
        return ymd;
    }

    public static int stringToDate(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int timeInt = 0;
        Date dateStart = null;
        try {
            dateStart = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        timeInt = (int) (dateStart.getTime() / 1000);
        return timeInt;
    }

    public static long getSelectEndDayTime(int year, int month, int day) {
        Calendar ca = Calendar.getInstance();
        ca.set(year, month, day, 23, 59, 59);
        Date time = ca.getTime();
        return time.getTime() / 1000;
    }

    public static String getTimeOfMonthStart() {
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.HOUR_OF_DAY, 0);
        ca.clear(Calendar.MINUTE);
        ca.clear(Calendar.SECOND);
        ca.clear(Calendar.MILLISECOND);
        ca.set(Calendar.DAY_OF_MONTH, 1);
        int year = ca.get(Calendar.YEAR);
        int month = ca.get(Calendar.MONTH) + 1;
        int day = ca.get(Calendar.DATE);
        String monthS = "";
        String dayS = "";
        if (month < 10) {
            monthS = "0" + month;
        } else {
            monthS = String.valueOf(month);
        }
        if (day < 10) {
            dayS = "0" + day;
        } else {
            dayS = String.valueOf(day);
        }
        return year + "-" + monthS + "-" + dayS;
    }

    public static String getTodayTimeYMD() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        return formatter.format(date);
    }

    public static String getTodayTimeYM() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM");
        Date date = new Date(System.currentTimeMillis());
        return formatter.format(date);
    }

    public static int getTodayTimeZero() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date zero = calendar.getTime();
        return (int) (zero.getTime() / 1000);
    }

    public static String getLastNMonthString(int lastNum) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH) - lastNum,
                1, 0, 0, 0);
        LogUtils.e(calendar.getTimeInMillis() + "");
        LogUtils.e(getTimeFormatted((calendar.getTimeInMillis() / 1000), "yyyy年MM月"));
        return getTimeFormatted((calendar.getTimeInMillis() / 1000), "yyyy年MM月");
    }

    /*
     * 毫秒转化时分秒
     */
    public static String formatTimeHMS(Long ms) {
        Integer ss = 1000;
        Integer mi = ss * 60;
        Integer hh = mi * 60;
        Integer dd = hh * 24;
        Long day = ms / dd;
        Long hour = (ms - day * dd) / hh;
        Long minute = (ms - day * dd - hour * hh) / mi;
        Long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        Long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;//毫秒
        StringBuffer sb = new StringBuffer();
        if (day > 0) {
            sb.append(day + "天");
        }
        if (hour > 0) {
            if (hour < 10) {
                sb.append("0");
            }
            sb.append(hour + "时");
        }
        if (minute > 0) {
            if (minute < 10) {
                sb.append("0");
            }
            sb.append(minute + "分");
        }
        if (second > 0) {
            if (second < 10) {
                sb.append("0");
            }
            sb.append(second + "秒");
        }
        return sb.toString();
    }

    //使用时长 超过小时去掉秒,超过天去掉分和秒,天数>99显示 99+天
    public static String longToUseTime(long ms) {
        Integer ss = 1000;
        Integer mi = ss * 60;
        Integer hh = mi * 60;
        Integer dd = hh * 24;
        Long day = ms / dd;
        Long hour = (ms - day * dd) / hh;
        Long minute = (ms - day * dd - hour * hh) / mi;
        Long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        Long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;//毫秒
        StringBuffer sb = new StringBuffer();
        if (day > 99) {
            sb.append("99+天");
            return sb.toString();
        } else if (day > 0) {
            sb.append(day + "天");
        }

        if (hour > 0) {
            if (hour < 10) {
                sb.append("0");
            }
            sb.append(hour + "时");
        }

        if (minute > 0 && day == 0) {
            if (minute < 10) {
                sb.append("0");
            }
            sb.append(minute + "分");
        }
        if (second > 0 && day == 0 && hour == 0) {
            if (second < 10) {
                sb.append("0");
            }
            sb.append(second + "秒");
        }
        if (StringUtil.isEmpty(sb.toString())) {
            sb.append("0秒");
        }
        return sb.toString();
    }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,444评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,421评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,036评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,363评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,460评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,502评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,511评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,280评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,736评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,014评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,190评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,848评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,531评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,159评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,411评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,067评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,078评论 2 352

推荐阅读更多精彩内容