时间的转换


SimpleDateFormat是线程不安全的,项目中会检测到SimpleDateFormat有时间格式缺陷,都替换为DateTimeFormatter
各种格式转化的方法

DateTimeFormatter

LocalDateTime与String日期互相转换

//字符串要和yyyy-MM-dd HH:mm:ss格式一样,否则报错
public static void main(String[] args) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //当前时间
        LocalDateTime time = LocalDateTime.now();
        //DateTimeFormatter转String
        String localTime = df.format(time);
        //String转DateTimeFormatter,第一个参数为String,第二个参数为时间格式
        LocalDateTime ldt = LocalDateTime.parse("2018-01-12 17:07:05",df);
        System.out.println("LocalDateTime转成String类型的时间:"+localTime);
        System.out.println("String类型的时间转成LocalDateTime:"+ldt);
    }
    String time1 = "2019-02-07 07:43:53";
        String time2 = "20190207074353";
        //时间
        //字符串转化
        DateTimeFormatter formater1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter formater2 = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

        LocalDateTime timeDate1=LocalDateTime.parse(time1, formater1);
        LocalDateTime timeDate2=LocalDateTime.parse(time2, formater2);
        //将指定格式的字符串转化为LocalDateTime
        //字符串格式1转日期==2019-02-07T07:43:53
        System.out.println("timeDate1==" + timeDate1);
        //字符串格式2转日期==2019-02-07T07:43:53
        System.out.println("timeDate2==" + timeDate2);

        //LocalDateTime=LocalDate+LocalTime
        LocalDate localDate = timeDate1.toLocalDate();
        LocalTime localTime = timeDate1.toLocalTime();
        //获取timeDate1年月日===2019-02-07
        System.out.println("timeDate1年月日===" + timeDate1.toLocalDate());
        //获取timeDate1时分秒===07:43:53
        System.out.println("timeDate1时分秒===" + timeDate1.toLocalTime());


        //MM 02月02日  M  2月2日
        DateTimeFormatter yearFormater = DateTimeFormatter.ofPattern("yyyy-M-d");
        DateTimeFormatter millFormater = DateTimeFormatter.ofPattern("HH:mm");
        //将日期按照指定格式  进行格式化
        String yearFor = localDate.format(yearFormater);
        String millFor = localTime.format(millFormater);
        //格式化日期2019-2-7===2019-2-7
        System.out.println("格式化日期2019-2-7===" + yearFor);
        //格式化日期07:43===07:43
        System.out.println("格式化日期07:43===" + millFor);
    }

在这里插入图片描述

yyyy-MM-dd HH:mm:ss 转成 yyyy-MM-dd

String类型的时间,转成对应格式的String
要获取String就dateFormat.format(date)
要获取Date就直接return date

    /**
     * 时间格式的字符串格式化
     * @param time 时间 2022-11-23 11:39:11
     * @param format 时间格式   yyyy-MM-dd
     * @return 转换后的时间 2022-11-23
     */
    public String timeFormat(String time,String format){
        DateFormat dateFormat = new SimpleDateFormat(format);
        Date date= new Date();
        try {
            date= dateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateFormat.format(date);
    }

格式化时间

        LocalDate localDate = LocalDate.now();
        String s1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println(s1);         //  20230619
        String s2 = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
        System.out.println(s2);     //  2023-06-19
        //自定义格式化
        DateTimeFormatter dateTimeFormatter =   DateTimeFormatter.ofPattern("dd/MM/yyyy");
        String s3 = localDate.format(dateTimeFormatter);
        System.out.println(s3);     //  19/06/2023

时间段拆分获取

2022-11-16 00:00:00 - 2022-12-16 23:59:59

    @Test
    void test3(){
        String time="2022-11-16 00:00:00 - 2022-12-16 23:59:59";
        //从第三个 -  开始拆分
        int index = getIndexOf(time, String.valueOf('-'), 3);
        //开始时间
        String start = time.substring(0,index);
        //结束时间
        String end=time.substring(index+1);
        System.out.println(start.trim());
        System.out.println(end.trim());


    }

    /**
     * @param data 指定字符串
     * @param str 需要定位的特殊字符或者字符串
     * @param num   第n次出现
     * @return  第n次出现的位置索引
     */
    public static int getIndexOf(String data,String str,int num){
        Pattern pattern = Pattern.compile(str);
        Matcher findMatcher = pattern.matcher(data);
        //标记遍历字符串的位置
        int indexNum=0;
        while(findMatcher.find()) {
            indexNum++;
            if(indexNum==num){
                break;
            }
        }
        return findMatcher.start();
    }

在这里插入图片描述

获取天数

    @Test
    void test5(){
        String date="2022-11-16 00:00:00 - 2022-12-18 23:59:59";
        int index = getIndexOf(date, String.valueOf('-'), 3);
        String start = date.substring(0,index);
        String end=date.substring(index+1);
        start=timeFormat(start,"yyyy-MM-dd");
        end=timeFormat(end,"yyyy-MM-dd");
        int numDays = Period.between( LocalDate.parse(start), LocalDate.parse(end)).getDays();
        //16一天,17一天,18一天,共三天,
        numDays++;
        System.out.println(numDays);
    }

在这里插入图片描述

Date

判断两个日期大小

三种方法

    @Test
    void test6() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1=new Date();
        Date date2 = sdf.parse("2023-12-11 10:44:12");

        /**
         * 一、compare方法
         *     返回值:
         *     date1小于date2返回-1,date1大于date2返回1,相等返回0
         */
        System.out.println(date1.compareTo(date2));

        /**
         * 二、Date的before()或者after()
         */
        System.out.println("date1在date2之后:"+date1.before(date2));
        System.out.println("date2在date1之后:"+date2.before(date1));

        /**
         * 三、毫秒数对比
         */
        long m1 = date1.getTime();
        long m2 = date2.getTime();

        System.out.println("date1>date2:"+(m1 > m2));

    }

在这里插入图片描述

判断两个日期相差几天

    @Test
    public void test5() throws Exception {
    
        String time1="2023-06-09 00:00:00 - 2023-06-12 11:59:59";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String[] times = time1.split(" - ");
        Date date1 = sdf.parse(times[0]);
        Date date2 = sdf.parse(times[1]);
        long diffInMillies = Math.abs(date2.getTime() - date1.getTime());
        long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
        System.out.println(diff);

    }

LocalDateTime和Date互转

LocalDateTime转Date

LocalDateTime localDateTime = LocalDateTime.now();

Date date = Date.from( localDateTime.atZone( ZoneId.systemDefault()).toInstant());

Date转LocalDateTime

Date todayDate = new Date();

LocalDateTime ldt = todayDate.toInstant()
        .atZone( ZoneId.systemDefault() )
        .toLocalDateTime();

LocalDate

只能获取年月日

        //获取当前年月日
        LocalDate localDate = LocalDate.now();
        //构造指定的年月日
        LocalDate localDate1 = LocalDate.of(2022, 10, 10);
        System.out.println(localDate);
        System.out.println(localDate1);
        

两种方式,直接get对应属性,还有一种方式,使用ChronoField,get枚举值:http://t.csdn.cn/e6R3c

        //获取当前年月日
        LocalDate localDate = LocalDate.now();
        //可以通过getYear,也可以通过ChronoField
        int year = localDate.getYear();
        int year1 = localDate.get(ChronoField.YEAR);
        System.out.println(year+"----------"+year1);

        Month month = localDate.getMonth();
        int month1 = localDate.get(ChronoField.MONTH_OF_YEAR);
        System.out.println("几月--------"+month1);

        int day = localDate.getDayOfMonth();
        System.out.println("几号--------"+day);

        int day1 = localDate.get(ChronoField.DAY_OF_MONTH);
        System.out.println("几号--------"+day1);

        DayOfWeek dayOfWeek = localDate.getDayOfWeek();
        int dayOfWeek1 = localDate.get(ChronoField.DAY_OF_WEEK);
        System.out.println("星期几--------"+dayOfWeek1);

LocalTime

只能获得几点几分几秒

        //获取时分秒
        LocalTime localTime = LocalTime.of(11, 11, 11);
        System.out.println(localTime);
        LocalTime localTime1 = LocalTime.now();
        System.out.println(localTime1);
        
        //获取小时
        int hour = localTime1.getHour();
        int hour1 = localTime1.get(ChronoField.HOUR_OF_DAY);
        System.out.println(hour+"----------"+hour1);
        
        //获取分
        int minute = localTime1.getMinute();
        int minute1 = localTime1.get(ChronoField.MINUTE_OF_HOUR);
        System.out.println(minute+"----------"+minute1);
        
        //获取秒
        int second = localTime1.getSecond();
        int second1 = localTime1.get(ChronoField.SECOND_OF_MINUTE);
        System.out.println(second+"----------"+second1);

LocalDateTime

获取年月日时分秒

        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);      //2023-06-19T15:04:40.722702400

        LocalDateTime localDateTime1 = LocalDateTime.of(2022, Month.SEPTEMBER, 5, 20, 37, 15);
        System.out.println(localDateTime1);     //2022-09-05T20:37:15

        LocalDateTime localDateTime2 = LocalDateTime.of(LocalDate.now(), LocalTime.now());
        System.out.println(localDateTime2);     //2023-06-19T15:04:40.723700200

        LocalDateTime localDateTime3 = LocalDate.now().atTime(LocalTime.now());
        System.out.println(localDateTime3);     //2023-06-19T15:04:40.723700200

        LocalDateTime localDateTime4 = LocalTime.now().atDate(LocalDate.now());
        System.out.println(localDateTime4);     //2023-06-19T15:04:40.723700200

获取LocalDate和获取LocalTime

        LocalDateTime localDateTime = LocalDateTime.now();
        //获取LocalDate
        System.out.println(localDateTime.toLocalDate());        //2023-06-19
        //获取LocalTime
        System.out.println(localDateTime.toLocalTime());        //15:06:27.867593700

Instant

获取秒数,可以直接用System.currentTimeMillis()

        Instant instant = Instant.now();
        System.out.println(instant);    //2023-06-19T07:10:28.484709300Z
        //获取秒
        System.out.println(instant.getEpochSecond());       //1687158628
        //获取毫秒
        System.out.println(instant.toEpochMilli());         //1687158628484

        System.out.println(System.currentTimeMillis());     // 1687158628491 

修改LocalDate、LocalTime、LocalDateTime、Instant

修改后返回一个新对象

通过minus和plus,增减时间

        LocalDateTime localDateTime = LocalDateTime.now();
        //获取LocalDate
        System.out.println(localDateTime.toLocalDate());        //2023-06-19
        //加一年,也可以用localDateTime.plus(1, ChronoUnit.YEARS);
        LocalDateTime localDateTime1 = localDateTime.plusYears(1);  //2024-06-19
        System.out.println(localDateTime1);
        //减一个月,localDateTime.minus(1, ChronoUnit.MONTHS);
        LocalDateTime localDateTime2 = localDateTime.minusMonths(1);
        System.out.println(localDateTime2);     //2023-05-19

通过with修改

可以修改年、月、日

        LocalDateTime localDateTime = LocalDateTime.now();
        //获取LocalDate
        System.out.println(localDateTime.toLocalDate());        //2023-06-19
        //改年份为2050年
        LocalDateTime localDateTime1 = localDateTime.withYear(2050);
        System.out.println(localDateTime1);         //2050-06-19
        //改年份为2060年
        LocalDateTime localDateTime2 = localDateTime.with(ChronoField.YEAR, 2060);
        System.out.println(localDateTime2);     //2060-06-19

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值