时间和字符串系列

1.时间转为字符串 Date—>String

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = simpleDateFormat.format(new Date());
System.out.println("时间转为字符串"+format);

输出结果:时间转为字符串2019-11-24 20:36:04

2.字符串转为时间 String—>Date

方式一:

 SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parse = simpleDateFormat2.parse("");
System.out.println("子串串转为时间"+parse);
>输出结果   :子串串转为时间Sun Nov 24 20:36:04 CST 2019

3.借助工具转换 Date<---->String

//pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
String strDate = DateFormatUtils.format(new Date(), pattern);
Date date = DateUtil.parseYYYYMMDDDate("2019-08-12")

4.比较日期相差天数

/**
* 比较两个日期相差的天数date2-date1
*/
    public int differentDays(Date date1,Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        //同一年
        if(year1 != year2)
        {
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++) {
                //闰年
                if(i%4==0 && i%100!=0 || i%400==0) {
                    timeDistance += 366;
                } else {//不是闰年
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2-day1) ;
        } else{    //不同年
            System.out.println("判断day2 - day1 : " + (day2-day1));
            return day2-day1;
        }
    }

5.在Date时间上加固定天数

/**
* date:初始时间,
* day:所加的天数
*/
    public Date TimeTransition(Date date,Integer day){

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, day);
        date = calendar.getTime();
        return date;
    }

6.时间戳 与 时间 转换

时间–>时间戳

Date date = simpleDateFormat.parse(time);
long ts = date.getTime();

时间戳–>时间

Date date = new Date(Long time);

发布了31 篇原创文章 · 获赞 3 · 访问量 899

猜你喜欢

转载自blog.csdn.net/S_L__/article/details/103228751