Android开发——时间相关工具类 时间戳转特定格式、事件类型转换、偏移时间差、计算时间差等等

在开发中, 时间转换、 获取时间差、计算前几小时等经常用到,写此博客以便记录,下次方便使用;

此工具类包含

时间戳转特定格式:

时间戳转成特定格式时间
获取milliseconds表示的日期时间的字符串.

String 和 Date 时间类型的转换:

String类型的日期时间转化为Date类型.
Date类型转化为String类型

String 和 Date 时间类型 获取偏移之后的日期:

获取当前系统前后第几天日期
获取当前系统前后第几小时日期
获取当前系统前后第几月
获取表示当前日期时间的字符串(可偏移).
获取指定时间的前后第几月
获取给定日期的偏移之后的Date. 如前几天 后几天 前几小时 后几小时等
获取指定日期时间的字符串偏移之后的字符串
Date类型转化为String类型  偏移之后的字符串

时间格式转换:

String类型的日期时间,导出想要的格式
获取指定日期时间的字符串,用于导出想要的格式.
获取表示当前日期时间的字符串格式.
获取表示当前日期时间的Date.

计算时间差:

计算两个日期所差的天数  (参数为毫秒值)
计算两个日期所差的小时数.(参数为毫秒值)
计算两个日期所差的分钟数.(参数为毫秒值)
计算两个日期所差的月数   (参数为Date类型)
计算两个日期所差的月数   (参数为String类型)
计算两个日期所差的年数.  (参数为Date类型)
计算两个日期所差的天数.  (参数为Date类型)
获取当前时间的本周一.     (参数为String类型)
获取本周的某一天.
获取本月第一天
获取本月最后一天.
获取表示当前日期的0点时间毫秒数.
获取表示当前日期24点时间毫秒数.
获取指定日期为星期几
指定时间距离当前多少个小时
指定时间距离当前过了多少个小时
判断给定字符串时间是否为今日  (参数为Date值)
判断给定字符串时间是否为今日  (参数为毫秒值)
根据用户生日计算年龄
根据时间返回几天前或几分钟的描述.
友好显示时间差
友好的时间间隔
通过日期来确定星座
返回聊天时间
获取指定时间的毫秒值
两个日期比较
代码如下:
/*
 * 
 */
package com.jstyle.jmnews.myapplication.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 {
    //一天的毫秒数
    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 dateFormatYMD = "yyyy-MM-dd";
    public static String dateFormatYMDofChinese = "yyyy年MM月dd日";

    /**
     * 时间日期格式化到年月日时分.中文显示
     */
    public static String dateFormatYMDHMofChinese = "yyyy年MM月dd日 HH:mm";
    public static String dateFormat = "yyyy-MM-dd HH:mm";
    /**
     * 时间日期格式化到月日.中文显示
     */
    public static String dateFormatMDofChinese = "MM月dd日";
    /**
     * 时间日期格式化到月.中文显示
     */
    public static String dateFormatMofChinese = "MM月";
    /**
     * 时间日期格式化到年月.
     */
    public static String dateFormatYM = "yyyy-MM";
    public static String dateFormatYMnian = "yyyy年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";


    //  ----------------------------------------------------时间戳转特定格式时间------------------------------------------------

    /**
     * 时间戳转特定格式时间
     *
     * @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));
    }

    /**
     * 时间戳转特定格式时间
     *
     * @param dataFormat 时间格式
     * @param timeStamp  时间毫秒数
     * @return
     */
    public static String formatDataMsec(String dataFormat, long timeStamp) {
        if (timeStamp == 0) {
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat(dataFormat);
        return format.format(new Date(timeStamp));
    }

    /**
     * 描述:获取milliseconds表示的日期时间的字符串.
     *
     * @param milliseconds 毫秒数 如10012344444444L
     * @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;
    }


    //  ----------------------------------------------------String 和 Date 类型转换 ------------------------------------------------

    /**
     * 描述:String类型的日期时间转化为Date类型.
     *
     * @param strDate String形式的日期时间 如:2012-03-22 13:11:00
     * @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类型转化为String类型.
     *
     * @param date   Date类型日期时间
     * @param format 格式化字符串,如:"yyyy-MM-dd HH:mm:ss"
     * @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;
    }

    //  ----------------------------------------------------String 和 Date 类型日期获取偏移之后的日期  (前后几天或者几小时对应的的日期)------------------------------------------------


    /**
     * 描述:获取当前系统前后第几天日期
     *
     * @param i      整数(值大于0,表示+,值小于0,表示-) 如 -20表示此日期的前20天,10 表示此日期的后10天
     * @param format 格式化字符串,如:"yyyy-MM-dd HH:mm:ss"
     * @return String String类型的当前日期时间
     */
    public static String getNextDay(int i, String format) {
        String curDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            Calendar c = new GregorianCalendar();
            c.add(Calendar.DAY_OF_MONTH, i);
            curDateTime = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }

    /**
     * 描述:获取当前系统前后第几小时日期
     *
     * @param i      整数(值大于0,表示+,值小于0,表示-) 如 -20表示此日期的前20小时,10 表示此日期的后10小时
     * @param format 格式化字符串,如:"yyyy-MM-dd HH:mm:ss"
     * @return String String类型的当前日期时间
     */
    public static String getNextHour(int i, String format) {
        String curDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            Calendar c = new GregorianCalendar();
            c.add(Calendar.HOUR_OF_DAY, i);
            curDateTime = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }

    /**
     * 描述:获取当前系统前后第几月
     *
     * @param i      整数(值大于0,表示+,值小于0,表示-) 如 -20表示20月前的日期,10 表示此日期的后10个月
     * @param format 格式化字符串,如:"yyyy-MM-dd HH:mm:ss"
     * @return String String类型的当前日期时间
     */
    public static String getNextMonth(int i, String format) {
        String curDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            Calendar c = new GregorianCalendar();
            c.add(Calendar.MONTH, 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;

    }

    /**
     * 描述:获取指定时间的前后第几月
     *
     * @param starttime 指定时间 如:"2018-01-30"
     * @param i         整数(值大于0,表示+,值小于0,表示-) 如 -20表示20月前的日期,10 表示此日期的后10个月
     * @param format    格式化字符串, 必须与指定时间格式一样 ,如:"yyyy-MM-dd"
     * @return String String类型的当前日期时间 如:"2018-02-28"
     */
    public static String getNextMonth(String starttime, int i, String format) {

        String curDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            Date date = mSimpleDateFormat.parse(starttime);
            Calendar c = new GregorianCalendar();
            c.setTime(date);
            c.add(Calendar.MONTH, i);
            curDateTime = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }

    /**
     * 描述:获取给定日期的偏移之后的Date. 如前几天 后几天 前几小时 后几小时等
     *
     * @param date          日期时间
     * @param calendarField Calendar属性,对应offset的值, 如(Calendar.DATE,表示+offset天,Calendar.HOUR_OF_DAY,表示+offset小时)
     * @param offset        偏移(值大于0,表示+,值小于0,表示-) 如 -20表示此日期的前20天或者20小时对应的日期,10 表示此日期的后10天或者10小时对应的日期等
     * @return Date 偏移之后的日期时间
     */
    public static 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,表示-)如 -20表示此日期的前20天或者20小时对应的日期,10 表示此日期的后10天或者10小时对应的日期等
     * @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类型转化为String类型  偏移之后的字符串
     *
     * @param date          日期时间
     * @param format        时间日期对应的格式化字符串,如:"yyyy-MM-dd HH:mm:ss"
     * @param calendarField Calendar属性,对应offset的值, 如(Calendar.DATE,表示+offset天,Calendar.HOUR_OF_DAY,表示+offset小时)
     * @param offset        偏移(值大于0,表示+,值小于0,表示-)如 -20表示此日期的前20天或者20小时对应的日期,10 表示此日期的后10天或者10小时对应的日期等
     * @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;
    }


    //  ----------------------------------------------------导出想要的时间格式----------------------------------------

    /**
     * 描述:String类型的日期时间,导出想要的格式
     *
     * @param strDate     String形式的日期时间 如:2012-03-22 13:11:00
     * @param format      日期时间对应的格式化字符串,如:"yyyy-MM-dd HH:mm:ss"
     * @param afterformat 输出的格式化字符串,如:"yyyy-MM-dd"
     * @return String String类型日期时间 如: 2012-03-22
     */
    public static String formatDate(String before, String format, String afterformat) {
        String after;
        try {
            Date date = new SimpleDateFormat(format, Locale.getDefault())
                    .parse(before);
            after = new SimpleDateFormat(afterformat, Locale.getDefault()).format(date);
        } catch (ParseException e) {
            return before;
        }
        return after;
    }


    /**
     * 描述:获取指定日期时间的字符串,用于导出想要的格式.
     *
     * @param strDate String形式的日期时间,必须为yyyy-MM-dd HH:mm:ss格式 如:2012-03-22 13:11:00
     * @param format  输出格式化字符串,如:"yyyy-MM-dd"
     * @return String 转换后的String类型的日期时间如: 2012-03-22
     */
    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;
    }


    /**
     * 描述:获取表示当前日期时间的字符串格式.
     *
     * @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;

    }

    /**
     * 描述:获取表示当前日期时间的Date.
     *
     * @return Date Date类型的当前日期时间
     */
    public static Date getCurrentDateFormat() {
        Date curDateTime = null;
        try {
            curDateTime = new Date(System.currentTimeMillis());//获取当前时间
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }

    //  ----------------------------------------------------计算时间差----------------------------------------

    /**
     * 描述:计算两个日期所差的天数.
     *
     * @param date1 第一个时间的毫秒表示  如:100000000L
     * @param date2 第二个时间的毫秒表示  如:200000000L
     * @return int 所差的天数  (当date2 > date1 时  值为 负值)      (当date2 < date1 时  值为 正值 )
     */
    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;
    }

    /**
     * 描述:计算两个日期所差的小时数.
     *
     * @param date1 第一个时间的毫秒表示
     * @param date2 第二个时间的毫秒表示
     * @return int 所差的小时数 (当date2 > date1 时  值为 负值)      (当date2 < date1 时  值为 正值 )
     */
    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;
    }

    /**
     * 描述:计算两个日期所差的分钟数.
     *
     * @param date1 第一个时间的毫秒表示
     * @param date2 第二个时间的毫秒表示
     * @return int 所差的分钟数 (当date2 > date1 时  值为 负值)      (当date2 < date1 时  值为 正值 )
     */
    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 fromDate 第一个时间的Date表示 起始时间
     * @param toDate   第二个时间的Date表示    结束时间
     * @return int 所差的月数 (fromDate > toDate 时  值为 负值)      (fromDate < toDate 时  值为 正值 )
     */
    public static int getOffectMonth(Date fromDate, Date toDate) {
        Calendar from = Calendar.getInstance();
        from.setTime(fromDate);
        Calendar to = Calendar.getInstance();
        to.setTime(toDate);
        //只要年月
        int fromYear = from.get(Calendar.YEAR);
        int fromMonth = from.get(Calendar.MONTH);
        int toYear = to.get(Calendar.YEAR);
        int toMonth = to.get(Calendar.MONTH);
        int month = toYear * 12 + toMonth - (fromYear * 12 + fromMonth);
        int day = (int) ((to.getTimeInMillis() - from.getTimeInMillis()) / (24 * 3600 * 1000));
        return month;
    }

    /**
     * 描述:计算两个日期所差的月数.
     *
     * @param fromtime   第一个时间的String表示
     * @param fromformat 第一个时间所对应的格式化
     * @param totime     第二个时间的String表示
     * @param toformat   第二个时间所对应的格式化
     * @return int 所差的月数 (fromDate > toDate 时  值为 负值)      (fromDate < toDate 时  值为 正值 )
     */
    public static int getOffectMonth(String fromtime, String fromformat, String totime, String toformat) {
        SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(fromformat);
        SimpleDateFormat mtoSimpleDateFormat = new SimpleDateFormat(toformat);
        Date fromDate = null;
        Date toDate = null;
        try {
            fromDate = mSimpleDateFormat.parse(fromtime);
            toDate = mtoSimpleDateFormat.parse(totime);
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        Calendar from = Calendar.getInstance();
        from.setTime(fromDate);
        Calendar to = Calendar.getInstance();
        to.setTime(toDate);
        //只要年月
        int fromYear = from.get(Calendar.YEAR);
        int fromMonth = from.get(Calendar.MONTH);
        int toYear = to.get(Calendar.YEAR);
        int toMonth = to.get(Calendar.MONTH);
        int month = toYear * 12 + toMonth - (fromYear * 12 + fromMonth);
        int day = (int) ((to.getTimeInMillis() - from.getTimeInMillis()) / (24 * 3600 * 1000));
        return month;
    }

    /**
     * 描述:计算两个日期所差的年数.
     *
     * @param fromDate 第一个时间的Date表示 起始时间
     * @param toDate   第二个时间的Date表示    结束时间
     * @return int 所差的年数 (fromDate > toDate 时  值为 负值)      (fromDate < toDate 时  值为 正值 )
     */
    public static int getOffectyear(Date fromDate, Date toDate) {
        Calendar from = Calendar.getInstance();
        from.setTime(fromDate);
        Calendar to = Calendar.getInstance();
        to.setTime(toDate);
        //只要年月
        int fromYear = from.get(Calendar.YEAR);
        int toYear = to.get(Calendar.YEAR);
        int year = toYear - fromYear;
        return year;
    }

    /**
     * 描述:计算两个日期所差的天数.
     *
     * @param fromDate 第一个时间的Date表示 起始时间
     * @param toDate   第二个时间的Date表示    结束时间
     * @return int 所差的天数 (fromDate > toDate 时  值为 负值)      (fromDate < toDate 时  值为 正值 )
     */
    public static int getOffectday(Date fromDate, Date toDate) {
        Calendar from = Calendar.getInstance();
        from.setTime(fromDate);
        Calendar to = Calendar.getInstance();
        to.setTime(toDate);
        int day = (int) ((to.getTimeInMillis() - from.getTimeInMillis()) / (24 * 3600 * 1000));
        return day;
    }

    /**
     * 描述:获取当前时间的本周一.
     *
     * @param format 时间格式化
     * @return String String类型日期时间
     */
    public static String getFirstDayOfWeek(String format) {
        return getDayOfWeek(format, Calendar.MONDAY);
    }

    /**
     * 描述:获取当前时间的本周日.
     *
     * @param format 时间格式化
     * @return String String类型日期时间
     */
    public static String getLastDayOfWeek(String format) {
        return getDayOfWeek(format, Calendar.SUNDAY);
    }

    /**
     * 描述:获取本周的某一天.
     *
     * @param format        the format
     * @param calendarField Calendar.SUNDAY  星期天 Calendar.MONDAY 星期一  Calendar.TUESDAY  星期二
     * @return String String类型日期时间
     */
    public 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点时间毫秒数.
     *
     * @return long 当前0点的毫秒数
     */
    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点时间毫秒数.
     *
     * @return long 当前24点的毫秒数 即第二天的0点
     */
    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 年代(如2016)
     * @return boolean 是否为闰年
     */
    public static boolean isLeapYear(int year) {
        if ((year % 4 == 0 && year % 400 != 0) || year % 400 == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取指定日期为星期几
     *
     * @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;
    }

    /**
     * 指定时间距离当前多少个小时
     *
     * @param dateStr 指定时间
     * @return int  当指定时间是当前时间的前面时,返回的是负值  如:2018-05-23 10:00:00    当前时间为2018-05-23 11:00:00  值为 -1
     */
    @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 int
     */
    @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());
            long times = dateNow.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();
        }
        return ret;
    }


    /**
     * 判断给定字符串时间是否为今日
     *
     * @param sdate  指定时间
     * @param fromat 指定时间的格式化
     * @return boolean
     */
    public static boolean isToday(String sdate, String fromat) {
        boolean b = false;
        Date time = null;
        SimpleDateFormat msimpleDateFormat = new SimpleDateFormat(fromat);
        try {
            time = msimpleDateFormat.parse(sdate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date today = new Date();
        SimpleDateFormat msimpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        if (time != null) {
            String nowDate = msimpleDateFormat1.format(today);
            String timeDate = msimpleDateFormat1.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();
        SimpleDateFormat msimpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        if (time != null) {
            String nowDate = msimpleDateFormat1.format(today);
            String timeDate = msimpleDateFormat1.format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 根据用户生日计算年龄
     */
    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) {
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                age--;
            }
        }
        return age;
    }

    /**
     * 描述:根据时间返回几天前或几分钟的描述.
     *
     * @param strDate Sting类型的时间
     * @param format  Sting类型的时间对应的格式化
     * @return the string
     */
    public static String formatDateStr2Desc(String strDate, String format) {

        DateFormat df = new SimpleDateFormat(format);
        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 "前天";
                }
                return d + "天前";
            } else if (d < 0) {
                if (d == -1) {
                    return "明天";
                } else if (d == -2) {
                    return "后天";
                }
                return Math.abs(d) + "天后";
            }
        } catch (Exception e) {
        }

        return strDate;
    }

    /**
     * 友好显示时间差
     *
     * @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;
    }


}

若有不完善 欢迎补充

猜你喜欢

转载自blog.csdn.net/shanshan_1117/article/details/80418743
今日推荐