Android关于日期的那点事(持续更新)

前言:
在实际开发中,当时间用于显示时,非特殊要求下一般使用系统默认的时区时间作为显示时间。将时间做为数据存储或传递给其他系统时(特别是跨平台调用),则最好使用标准的UTC/GMT时间(后面统称GMT),除非事先约定或标识了时间的类型。

1、日期
①:String timeInMillsTransToDate(int formatType) 获取当前的时间(年月日时分秒)
结果:
0:2020年05月02日 15时:16分:05秒
1:2020-05-02T15:16:05+0800
2:2020-05-02 15:16:05

②:long getCurrentTimeMillis(int formatType) 获取当前的时间戳(精确到秒/1000)
结果:
1588145236587(3种方式都是一样的)
那有何区别?这里我分别打印10万次看哪种耗时最短
第一种:2527
第二种:4260
第三种:3321
总结:第一种方式获取速度最快,但是当我做3万次的时候第三种最快
所以在小量情况下1、3时间是差不多的,2由于Canlendar要处理时区所以最慢

③:String timeTimeMillis(long millis) 时间戳转换成日期格式字符串
时间戳转换成日期格式字符串()

millis 精确到秒的字符串
传入:getCurrentTimeMillis(0)/1000
结果:2020-05-2 16:33:03

④:String timeTimeMillis(String date) 日期格式字符串转换成时间戳
date 字符串日期(2020-05-02 15:30:00)

结果:1588404600

⑤:String getTimeRange(String mTime) 格式化时间 (返回几秒、几分钟前等)
传入:2020-05-02 15:30:00 运行时间2020-05-01
结果:1天前

⑥:String getDateFormat(int counts) 秒数转换时间格式
counts 秒数 :4500秒(1小时15分钟)
结果:01:15:00

2、LocalDateTime的简单使用与介绍
LocalDate、LocalTime、LocalDateTime【java8新提供的类】
java8新的时间API的使用方式,包括创建、格式化、解析、计算、修改

//获取年月日 2020-05-07
LocalDate localDate = LocalDate.now();
//获取时分秒毫秒 13:49:31.549
LocalTime localDate1 = LocalTime.now();
//获取年月日时分秒 2020-05-07T13:49:31.549
LocalDateTime localDate2 = LocalDateTime.now();

①:getTimeLocalDateTime1(String time) 根据字符串获取年月日时分秒
传入:2020-05-25 12:34:56(注意月份补0)

方法描述
getYear();/get(ChronoField.YEAR);获取年 2020
get(ChronoField.MONTH_OF_YEAR);获取月5
getMonth();获取(英文)月MAY
getDayOfMonth();/localDate.get(ChronoField.DAY_OF_MONTH)获取日25
getHour();获取时12
getMinute();获取分34
getSecond();获取秒56
getDayOfWeek();获取星期(英文)THURSDAY(周四)
get(ChronoField.DAY_OF_WEEK);获取星期4
.getDayOfWeek().getValue();该日期是当前周的第几天 4
.getDayOfMonth();该日期是当前月的第几天 4
getDayOfYear();该日期是当前年的第几天 128
withYear(2022);修改该日期的年份
withMonth(12);修改该日期的月份
withDayOfMonth(20);修改该在当前月的天数

②:时间判断、加减、比较

方法描述
.isLeapYear();判断是否是闰年 true
.lengthOfYear();判断该年是365天还是366天 366
.lengthOfMonth();当前月有多少天 31
plusYears(1);时间加上1年
plusMonths(1);时间加上1月
plusDays(1);时间加上1天
plusHours(1);时间加上1时
plusMinutes(1);时间加上1分
plusSeconds(1);时间加上1秒
minusYears (1);时间减去一年(月日时分秒同上)
compareTo时间比较(-1小于 0等于 1大于)

③:LocalDate 与 String 之间的互转(同理)
1、LocalDateTime today = LocalDateTime.now();
//指定转换格式
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss”);
//转化为string
String dateStr = today.format(fmt);

2、String str = “2020-05-10 15:20:00”;
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss”);
LocalDateTime date = LocalDateTime.parse(str, fmt);

④:2个string转化比较
//两个字符串时间比较大小
String str1 = “2020-05-10 15:20:00”;
String str2 = “2020-05-10 15:30:00”;
//进行转换
LocalDateTime date1 = LocalDateTime.parse(str1, fmt);
LocalDateTime date2 = LocalDateTime.parse(str2, fmt);
//比较大小 (返回值-1、0、1)
int compareTo = date1.compareTo(date2);

3、日历的简单使用
①:List getDateWeek() 获取本周的所有日期
例:
2020-05-02
2020-05-03
2020-05-04
2020-05-05
2020-05-06
2020-05-07
2020-05-08

②:List getCalendar(int year, int month) 根据年月获取上月月末 本月 以及下月初日历 (例:year:2020 month:5)

③:getCalendarThisMonthDay(int year, int month) 获取指定年月天数大小
例:year:2020 month:5 结果:31天

④:getWeekDay(String date) 根据当前日期获得是星期几
例:date:2020-05-20 结果:周三

⑤:getCalendarDay(int type) 获取特定日期
例:0 获取本月第一天
1 本月最后一天
2 下月月初

4、详细的使用方法工具类DateManagerUtils

/**
 * 功能描述:日期管理类
 */
public class DateManagerUtils {

    private static final String TAG = "DateManagerUtils";

    /**
     * 获取当前的时间(年月日时分秒)
     * 结果:
     * 2020年05月02日 15时:16分:05秒
     * 2020-05-02T15:16:05+0800
     * 2020-05-02 15:16:05
     */
    public static String timeInMillsTransToDate(int formatType) {
        DateFormat formatter = null;
        switch (formatType) {
            case 0:
                formatter = new SimpleDateFormat("yyyy年MM月dd日 HH时:mm分:ss秒");
                break;
            case 1:
                formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                break;
            case 2:
                formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                break;
        }
        Calendar calendar = Calendar.getInstance();
        return formatter.format(calendar.getTime());
    }

    /**
     * 获取当前的时间戳(精确到秒/1000)
     * 结果:
     * 1588145236587(3种方式都是一样的)
     * 那有何区别?这里我分别打印10万次看哪种耗时最短
     * 第一种:2527
     * 第二种:4260
     * 第三种:3321
     * 总结:第一种方式获取速度最快,但是当我做3万次的时候第三种最快
     * 所以在小量情况下1、3时间是差不多的,2由于Canlendar要处理时区所以最慢
     */
    public static long getCurrentTimeMillis(int formatType) {
        long timeMillis = 0;
        switch (formatType) {
            case 0:
                timeMillis = System.currentTimeMillis();
                break;
            case 1:
                timeMillis = Calendar.getInstance().getTimeInMillis();
                break;
            case 2:
                timeMillis = new Date().getTime();
                break;
        }
        return timeMillis;
    }

    /**
     * 时间戳转换成日期格式字符串()
     * millis 精确到秒的字符串
     * 传入:getCurrentTimeMillis(0)/1000
     * 结果:2020-05-2 16:33:03
     */
    public static String timeTimeMillis(long millis) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date(millis));
    }

    /**
     * 日期格式字符串转换成时间戳
     * date 字符串日期(2020-05-02 15:30:00)
     * 结果:1588404600
     */
    public static String timeTimeMillis(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            //精确到秒除以1000
            return String.valueOf(sdf.parse(date).getTime() / 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 设置每个阶段时间
     */
    private static final int seconds_of_1minute = 60;
    private static final int seconds_of_30minutes = 30 * 60;
    private static final int seconds_of_1hour = 60 * 60;
    private static final int seconds_of_1day = 24 * 60 * 60;
    private static final int seconds_of_15days = seconds_of_1day * 15;
    private static final int seconds_of_30days = seconds_of_1day * 30;
    private static final int seconds_of_6months = seconds_of_30days * 6;
    private static final int seconds_of_1year = seconds_of_30days * 12;

    /**
     * 格式化时间
     * 传入:2020-05-02 15:30:00  运行时间2020-05-01
     * 结果:1天前
     */
    public static String getTimeRange(String mTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        /**获取当前时间*/
        Date curDate = new Date(System.currentTimeMillis());
        String dataStrNew = sdf.format(curDate);
        Date startTime = null;
        try {
            /**将时间转化成Date*/
            curDate = sdf.parse(dataStrNew);
            startTime = sdf.parse(mTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        /**除以1000是为了转换成秒*/
        long between = (curDate.getTime() - startTime.getTime()) / 1000;
        int elapsedTime = (int) (between);
        Log.e(TAG, "getTimeRange: " + elapsedTime);
        //传入时间必须小于当前时间
        if (elapsedTime > 0) {
            if (elapsedTime < seconds_of_1minute) {
                return "刚刚";
            }
            if (elapsedTime < seconds_of_30minutes) {
                return elapsedTime / seconds_of_1minute + "分钟前";
            }
            if (elapsedTime < seconds_of_1hour) {
                return "半小时前";
            }
            if (elapsedTime < seconds_of_1day) {
                return elapsedTime / seconds_of_1hour + "小时前";
            }
            if (elapsedTime < seconds_of_15days) {
                return elapsedTime / seconds_of_1day + "天前";
            }
            if (elapsedTime < seconds_of_30days) {
                return mTime.substring(0, 10);
            }
            if (elapsedTime < seconds_of_30days) {
                return "半个月前";
            }
            if (elapsedTime < seconds_of_6months) {
                return elapsedTime / seconds_of_30days + "月前";
            }
            if (elapsedTime < seconds_of_1year) {
                return "半年前";
            }
            if (elapsedTime >= seconds_of_1year) {
                return elapsedTime / seconds_of_1year + "年前";
            }
        }
        return "时间格式错误!";
    }

    /**
     * 秒数转换时间格式
     * counts 秒数 :4500
     * 结果:01:15:00
     */
    public static String getDateFormat(int counts) {
        LogUtils.e("总秒数:" + counts);
        String timeStr;
        int hour;
        int minute;
        int second;
        if (counts <= 0)
            return "00:00";
        else {
            minute = counts / 60;
            if (minute < 60) {
                second = counts % 60;
                timeStr = getFormat(minute) + ":" + getFormat(second);
            } else {
                hour = minute / 60;
                if (hour > 99)
                    return "99:59:59";
                minute = minute % 60;
                second = counts - hour * 3600 - minute * 60;
                timeStr = getFormat(hour) + ":" + getFormat(minute) + ":" + getFormat(second);
            }
        }
        return timeStr;
    }

    /**
     * 是否需要补0
     */
    public static String getFormat(int i) {
        String retStr;
        if (i >= 0 && i < 10)
            retStr = "0" + i;
        else
            retStr = "" + i;
        return retStr;
    }

    /**
     * 根据字符串获取年月日时分秒
     * 传入:2020-05-25 12:34:56(注意月份补0)
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void getTimeLocalDateTime1(String time) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(time, df);
        //获取年
        int year = dateTime.getYear();
        //获取月
        int month = dateTime.get(ChronoField.MONTH_OF_YEAR);
        //获取日
        int day = dateTime.getDayOfMonth();
        获取时
        int hour = dateTime.getHour();
        //获取分
        int minute = dateTime.getMinute();
        //获取秒
        int second = dateTime.getSecond();

        Log.e(TAG, "getTimeLocalDateTime1: " + year);
        Log.e(TAG, "getTimeLocalDateTime1: " + month);
        Log.e(TAG, "getTimeLocalDateTime1: " + day);
        Log.e(TAG, "getTimeLocalDateTime1: " + hour);
        Log.e(TAG, "getTimeLocalDateTime1: " + minute);
        Log.e(TAG, "getTimeLocalDateTime1: " + second);
    }

    /**
     * 查询、修改年月日等
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void getTimeLocalDateTime2() {
        //获取年月日 2020-05-07
        LocalDate localDate = LocalDate.now();
        //获取时分秒毫秒 13:49:31.549
        LocalTime localDate1 = LocalTime.now();
        //获取年月日时分秒 2020-05-07T13:49:31.549
        LocalDateTime localDate2 = LocalDateTime.now();
        //构造指定的年月日 2020-05-10
        LocalDate localDate3 = LocalDate.of(2020, 5, 10);
        //2020
        int year = localDate.getYear();
        //2020
        int year1 = localDate.get(ChronoField.YEAR);
        //英文 例:5月 MAY
        Month month = localDate.getMonth();
        //5
        int month1 = localDate.get(ChronoField.MONTH_OF_YEAR);
        //7
        int day = localDate.getDayOfMonth();
        //7
        int day1 = localDate.get(ChronoField.DAY_OF_MONTH);
        //THURSDAY(周四)
        DayOfWeek dayOfWeek = localDate.getDayOfWeek();
        //4
        int dayOfWeek1 = localDate.get(ChronoField.DAY_OF_WEEK);
        //该日期是当前周的第几天 4
        int weekDay = localDate.getDayOfWeek().getValue();
        //该日期是当前月的第几天 7
        int monthDay = localDate.getDayOfMonth();
        //该日期是当前年的第几天 128
        int yearDay = localDate.getDayOfYear();
        //修改该日期的年份 2022-05-07
        LocalDate withYear = localDate.withYear(2022);
        //修改该日期的月份  2020-12-07
        LocalDate withMonth = localDate.withMonth(12);
        //修改该在当前月的天数 2020-05-20
        LocalDate withDay = localDate.withDayOfMonth(20);

        Log.e(TAG, "getTimeLocalDateTime2: " + localDate);
        Log.e(TAG, "getTimeLocalDateTime2: " + localDate1);
        Log.e(TAG, "getTimeLocalDateTime2: " + localDate2);
        Log.e(TAG, "getTimeLocalDateTime2: " + localDate3);
        Log.e(TAG, "getTimeLocalDateTime2: " + year);
        Log.e(TAG, "getTimeLocalDateTime2: " + year1);
        Log.e(TAG, "getTimeLocalDateTime2: " + month);
        Log.e(TAG, "getTimeLocalDateTime2: " + month1);
        Log.e(TAG, "getTimeLocalDateTime2: " + day);
        Log.e(TAG, "getTimeLocalDateTime2: " + day1);
        Log.e(TAG, "getTimeLocalDateTime2: " + dayOfWeek);
        Log.e(TAG, "getTimeLocalDateTime2: " + dayOfWeek1);
        Log.e(TAG, "getTimeLocalDateTime2: " + weekDay);
        Log.e(TAG, "getTimeLocalDateTime2: " + monthDay);
        Log.e(TAG, "getTimeLocalDateTime2: " + yearDay);
        Log.e(TAG, "getTimeLocalDateTime2: " + withYear);
        Log.e(TAG, "getTimeLocalDateTime2: " + withMonth);
        Log.e(TAG, "getTimeLocalDateTime2: " + withDay);
    }

    /**
     * 根据字符串获取年月日时分秒
     * 传入:2020-05-25 12:34:56(注意月份补0)
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void getTimeLocalDateTime3() {
        LocalDate localDate = LocalDate.now();
        //判断是否是闰年  true
        Log.e(TAG, "getTimeLocalDateTime3: " + localDate.isLeapYear());
        //判断改年是365天还是366天  366
        Log.e(TAG, "getTimeLocalDateTime3: " + localDate.lengthOfYear());
        //当前月有多少天 31
        Log.e(TAG, "getTimeLocalDateTime3: " + localDate.lengthOfMonth());

        LocalDateTime dateTime = LocalDateTime.now();
        //当前时间加上1小时作比较(可减年月日时分秒) -1
        int i1 = dateTime.compareTo(dateTime.plusHours(1));
        //当前时间减去1小时作比较(同上)1
        int i2 = dateTime.compareTo(dateTime.minusHours(1));
        //当前时间与当前时间比较 0
        int i3 = dateTime.compareTo(dateTime);

        //LocalDate 与 String 之间的转换
        LocalDateTime today = LocalDateTime.now();
        //指定转换格式
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //转化为string
        String dateStr = today.format(fmt);
        Log.e(TAG, "getTimeLocalDateTime3: " + dateStr);

        //两个字符串时间比较大小
        String str1 = "2020-05-10 15:20:00";
        String str2 = "2020-05-10 15:30:00";
        //进行转换
        LocalDateTime date1 = LocalDateTime.parse(str1, fmt);
        LocalDateTime date2 = LocalDateTime.parse(str2, fmt);
        //比较大小 (-1 date1比date2小)
        int compareTo = date1.compareTo(date2);

        Log.e(TAG, "getTimeLocalDateTime3: " + i1);
        Log.e(TAG, "getTimeLocalDateTime3: " + i2);
        Log.e(TAG, "getTimeLocalDateTime3: " + i3);
        Log.e(TAG, "getTimeLocalDateTime3: " + date1);
        Log.e(TAG, "getTimeLocalDateTime3: " + compareTo);
    }

    /**
     * 日历相关
     * 获取本周的所有日期
     */
    public static List<String> getDateWeek() {
        List<String> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //count 用来存取与当天日期的相差数
        int count;
        for (int i = 0; i < 7; i++) {
            //新建日历
            Calendar cal = Calendar.getInstance();
            //在日历中找到当前日期
            cal.setTime(cal.getTime());
            //当前日期是本周第几天,默认按照中国习惯星期一为一周的第一天(末尾的+1的由来)
            //count = -cal.get(Calendar.DAY_OF_WEEK) + 1;
            count = -cal.get(Calendar.DAY_OF_WEEK);
            //循环。当天与本周周一到周日相差的天数
            cal.add(Calendar.DATE, count + i);
            //转化格式
            String time = sdf.format(cal.getTime());
            list.add(time);
            //2020-05-02 (周六开始) 周一开始(改为i=2 i<10)
            //2020-05-03
            //2020-05-04
            //2020-05-05
            //2020-05-06
            //2020-05-07
            //2020-05-08
            Log.e(TAG, "getDateWeek: " + time);
        }
        return list;
    }

    /**
     * 根绝年月获取上月月末 本月 以及下月初日历
     * year:2020  month:5
     */
    public static List<String> getCalendar(int year, int month) {
        //实例化集合
        List<String> list = new ArrayList<>();
        Calendar c = Calendar.getInstance();
        c.clear();

        //处理上个月月末
        if (month - 1 == 0) {
            c.set(Calendar.YEAR, year - 1);
            c.set(Calendar.MONTH, 11);
        } else {
            c.set(Calendar.YEAR, year);
            c.set(Calendar.MONTH, (month - 2));
        }
        int last_sumDays = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        c.set(Calendar.DATE, last_sumDays);
        //得到一号星期几
        int weekDay = c.get(Calendar.DAY_OF_WEEK);
        if (weekDay < 7) {
            for (int i = weekDay - 1; i >= 0; i--) {
                Integer date = new Integer(last_sumDays - i);
                //26-30
                Log.e(TAG, "getCalendar: " + date);
            }
        }

        //处理当前月
        c.clear();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month - 1);
        int currentsumDays = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        for (int i = 1; i <= currentsumDays; i++) {
            Integer date = new Integer(i);
            //1-31
            Log.e(TAG, "getCalendar: " + date);
        }

        //处理下个月月初
        c.clear();
        if (month == 12) {
            c.set(Calendar.YEAR, year + 1);
            c.set(Calendar.MONTH, 0);
        } else {
            c.set(Calendar.YEAR, year);
            c.set(Calendar.MONTH, month);
        }
        c.set(Calendar.DATE, 1);
        int currentWeekDay = c.get(Calendar.DAY_OF_WEEK);
        if (currentWeekDay > 2 && currentWeekDay < 8) {
            for (int i = 1; i <= 8 - currentWeekDay; i++) {
                //0
                Log.e(TAG, "getCalendar: " + i);
            }
        }
        return list;
    }

    /**
     * 获取指定年月天数大小
     * year:2020  month:5
     */
    public static int getCalendarThisMonthDay(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.clear();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month - 1);
        int size = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        //31 天
        Log.e(TAG, "getCalendarThisMonth: " + size);
        return size;
    }

    /**
     * 根据当前日期获得是星期几
     * pTime:2020-05-20
     */
    public static String getWeekDay(String pTime) {
        String week = "";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(format.parse(pTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            week += "天";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 2) {
            week += "一";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 3) {
            week += "二";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 4) {
            week += "三";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 5) {
            week += "四";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 6) {
            week += "五";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 7) {
            week += "六";
        }
        //三
        Log.e(TAG, "getWeekDay: " + week);
        return week;
    }

    /**
     * 获取号数
     * 0 获取本月第一天
     * 1 本月最后一天
     * 2 下月月初
     */
    public static String getCalendarDay(int type) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        if (type == 0) {
            c.add(Calendar.MONTH, 0);
            c.set(Calendar.DAY_OF_MONTH, 1);//本月第一天
        } else if (type == 1) {
            c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));//本月最后一天
        } else if (type == 2) {
            c.add(Calendar.MONTH, 1);//月份设置为下个月
            c.set(Calendar.DAY_OF_MONTH, 1);//日期设置为1号
            c.add(Calendar.DAY_OF_MONTH, 0);//倒回到前一天
        }
        String date = format.format(c.getTime());
        Log.e(TAG, "getCalendarDay: " + date);
        return date;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值