Java学习笔记(五)——时间相关类

2024-01-07 18:58:36

JDK7以前时间相关类

在这里插入图片描述

Date 时间类

阅读源码

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

import java.util.Date;

public class test13 {
    public static void main(String[] args) {

        //空参构造
        Date date1=new Date();
        System.out.println(date1);  //Sat Jan 06 16:08:25 CST 2024

        //有参构造
        Date date2=new Date(0L);
        System.out.println(date2);  //Thu Jan 01 08:00:00 CST 1970 —— 东八区在0的基础上加8个小时
        
        //修改时间,传递的参数为毫秒
        date2.setTime(1000L);
        System.out.println(date2);  //Thu Jan 01 08:00:01 CST 1970 —— 1000ms=1s

        //获取时间的毫秒值
        System.out.println(date2.getTime());  //1000
        
    }
}

练习

需求1:打印时间原点开始一年之后的时间

import java.util.Date;

public class test14 {
    public static void main(String[] args) {
        Date date=new Date(0L);
        long time=365*24*60*60*1000L;
        date.setTime(time);
        System.out.println(date);  //Fri Jan 01 08:00:00 CST 1971
    }
}
import java.util.Date;

public class test14 {
    public static void main(String[] args) {
        Date date=new Date(0L);
        long time=date.getTime();
        time+=365*24*60*60*1000L;
        date.setTime(time);
        System.out.println(date);  //Fri Jan 01 08:00:00 CST 1971
    }
}

需求2:定义任意两个Date对象,比较哪个时间在前,哪个时间在后

import java.util.Date;
import java.util.Random;

public class test15 {
    public static void main(String[] args) {
        Random random = new Random();
        Date date1 = new Date(Math.abs(random.nextInt()));
        Date date2 = new Date(Math.abs(random.nextInt()));
        long time1 = date1.getTime();
        long time2 = date2.getTime();
        if (time1 < time2) {
            System.out.println("date1时间在前");
        } else if (time1 > time2) {
            System.out.println("date2时间在前");
        } else {
            System.out.println("date1和date2时间相同");
        }
    }
}

SimpleDateFormat 格式化时间

作用
  • 格式化:把时间变成想要的格式
  • 解析:把字符串表示的时间变成Date对象
构造方法

在这里插入图片描述

常用方法

在这里插入图片描述

日期和时间模式

在这里插入图片描述

在这里插入图片描述

import java.text.SimpleDateFormat;
import java.util.Date;

public class test16 {
    public static void main(String[] args) {
        SimpleDateFormat sdf1=new SimpleDateFormat();
        Date date=new Date(0L);
        String str1=sdf1.format(date);
        System.out.println(str1);  //70-1-1 上午8:00

        SimpleDateFormat sdf2=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String str2=sdf2.format(date);
        System.out.println(str2);  //1970年01月01日 08:00:00

        SimpleDateFormat sdf3=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss E");
        String str3=sdf3.format(date);
        System.out.println(str3);  //1970年01月01日 08:00:00 星期四
    }
}

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class test17 {
    public static void main(String[] args) throws ParseException {
        String str="2002-11-20 14:13:55";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(str);
        System.out.println(date);  //Wed Nov 20 14:13:55 CST 2002
    }
}
练习

需求1:

假设,你的猪的出生年月日为:2000-09-26,请用字符串表示这个数据,并将其转换为:2000年09月26日

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class test18 {
    public static void main(String[] args) throws ParseException {
        //假设,你猪的出生年月日为:2000-09-26,请用字符串表示这个数据,并将其转换为:2000年09月26日
        String str = "2000-09-26";
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf1.parse(str);

        SimpleDateFormat sdf2=new SimpleDateFormat("yyyy年MM月dd日");
        String result = sdf2.format(date);
        System.out.println(result);
    }
}

需求2:

在这里插入图片描述

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class test19 {
    public static void main(String[] args) throws ParseException {
        String time1 = "2023年11月11日 0:01:00";
        String time2 = "2023年11月11日 0:11:0";

        String start = "2023年11月11日 0:0:0";
        String end = "2023年11月11日 0:10:0";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        
        Date time1_date = sdf.parse(time1);
        Date time2_date = sdf.parse(time2);
        Date start_date = sdf.parse(start);
        Date end_date = sdf.parse(end);

        long time1_time = time1_date.getTime();
        long time2_time = time2_date.getTime();
        long start_time = start_date.getTime();
        long end_time = end_date.getTime();

        if (time1_time >= start_time && time1_time <= end_time) {
            System.out.println("小贾下单成功!");
        } else {
            System.out.println("小贾下单失败!");
        }

        if (time2_time >= start_time && time2_time <= end_time) {
            System.out.println("小皮下单成功!");
        } else {
            System.out.println("小皮下单失败!");
        }
        
    }
}

Calendar 日历

在这里插入图片描述

Calendar代表系统当前时间的日历对象,可以单独修改、获取时间中的年、月、日。

注意:Calendar是一个抽象类,不能直接创建对象。

获取Calendar对象的方法

在这里插入图片描述

Calendar常用方法

在这里插入图片描述

import java.util.Calendar;
import java.util.Date;

public class test20 {
    public static void main(String[] args) {

        //底层原理:会根据系统的不同时区返回不同的日历对象
        //把相关的信息放在一个数组当中
        Calendar calendar=Calendar.getInstance();

        //月份:范围0~11,MONTH=0是1月
        //星期:1是星期天,DAY_OF_WEEK=1是星期天
        System.out.println(calendar);
        // java.util.GregorianCalendar[time=1704565565855,areFieldsSet=true,areAllFieldsSet=true,
        // lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,
        // useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,
        // YEAR=2024,MONTH=0,WEEK_OF_YEAR=2,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=7,DAY_OF_WEEK=1,
        // DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=2,HOUR_OF_DAY=2,MINUTE=26,SECOND=5,MILLISECOND=855,
        // ZONE_OFFSET=28800000,DST_OFFSET=0]

        //修改日历代表时间
        Date date=new Date(0L);
        calendar.setTime(date);
        System.out.println(calendar);
        // java.util.GregorianCalendar[time=0,areFieldsSet=true,areAllFieldsSet=true,lenient=true,
        // zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,
        // transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=1970,MONTH=0,
        // WEEK_OF_YEAR=1,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=1,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=1,
        // AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=28800000,DST_OFFSET=0]

        //修改日历毫秒值
        calendar.setTimeInMillis(1000L);
        System.out.println(calendar);
        // java.util.GregorianCalendar[time=1000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,
        // zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,
        // transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=1970,MONTH=0,
        // WEEK_OF_YEAR=1,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=1,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=1,
        // AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=0,SECOND=1,MILLISECOND=0,ZONE_OFFSET=28800000,DST_OFFSET=0]

        //获取日历信息
        System.out.println(calendar.get(Calendar.YEAR));  //1970
        System.out.println(calendar.get(Calendar.MONTH));  //0
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));  //1

        //修改日历中指定信息的值
        calendar.set(Calendar.YEAR,2024);
        System.out.println(calendar);
        //java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,
        // zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,
        // transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2024,MONTH=0,
        // WEEK_OF_YEAR=1,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=1,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=1,
        // AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=0,SECOND=1,MILLISECOND=0,ZONE_OFFSET=28800000,DST_OFFSET=0]

        //某个字段增加指定值
        calendar.add(Calendar.YEAR,+5);
        System.out.println(calendar);
        // java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,
        // zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,
        // transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2029,MONTH=0,
        // WEEK_OF_YEAR=1,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=1,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=1,
        // AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=0,SECOND=1,MILLISECOND=0,ZONE_OFFSET=28800000,DST_OFFSET=0]

        //某个字段减少指定值
        calendar.add(Calendar.YEAR,-10);
        System.out.println(calendar);
        // java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,
        // zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,
        // transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2019,MONTH=0,
        // WEEK_OF_YEAR=1,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=1,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=1,
        // AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=0,SECOND=1,MILLISECOND=0,ZONE_OFFSET=28800000,DST_OFFSET=0]
    }
}

JDK8新增时间相关类

在这里插入图片描述

变化

在这里插入图片描述

Date类

ZoneId:时区

在这里插入图片描述

在这里插入图片描述

import java.time.ZoneId;
import java.util.Set;

public class test21 {
    public static void main(String[] args) {
        // 获取所有时区名称
        Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
        System.out.println(availableZoneIds);
        System.out.println(availableZoneIds.size());  //603

        // 获取当前系统时区
        ZoneId systemDefault = ZoneId.systemDefault();
        System.out.println(systemDefault);  //Asia/Shanghai

        // 获取指定时区
        ZoneId zoneId = ZoneId.of("America/Marigot");
        System.out.println(zoneId);  //America/Marigot
    }
}
Instant:时间戳

在这里插入图片描述

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class test22 {
    public static void main(String[] args) {
        // 获取世界标准时间
        Instant now = Instant.now();
        System.out.println(now);  //2024-01-06T19:24:29.595Z

        // 获取当前东八区时间
        ZoneId zoneId = ZoneId.of("Asia/Shanghai");
        ZonedDateTime now_eight=now.atZone(zoneId);
        System.out.println(now_eight);  //2024-01-07T03:24:29.595+08:00[Asia/Shanghai]

        // 根据毫秒获取Instant对象
        Instant ofEpochMilli = Instant.ofEpochMilli(1000L);
        System.out.println(ofEpochMilli);  //970-01-01T00:00:01Z

        // 根据秒获取Instant对象
        Instant ofEpochSecond = Instant.ofEpochSecond(40);
        System.out.println(ofEpochSecond);  //1970-01-01T00:00:40Z

        // 根据秒+纳秒获取Instant对象
        Instant ofEpochSecond1 = Instant.ofEpochSecond(20, 20);  //1970-01-01T00:00:20.000000020Z
        System.out.println(ofEpochSecond1);

        // 判断前后
        Instant instant1=Instant.ofEpochMilli(1000L);
        Instant instant2=Instant.ofEpochMilli(2000L);

        boolean result1=instant1.isAfter(instant2);  //false
        boolean result2=instant1.isBefore(instant2);  //true

        System.out.println(result1);
        System.out.println(result2);

        // 减少/增加
        Instant instant3=Instant.ofEpochMilli(3000L);
        Instant instant4=Instant.ofEpochMilli(4000L);

        Instant instant5=instant3.minusMillis(1000L);
        Instant instant6=instant4.plusMillis(1000L);

        System.out.println(instant3);  //1970-01-01T00:00:03Z
        System.out.println(instant4);  //1970-01-01T00:00:04Z
        System.out.println(instant5);  //1970-01-01T00:00:02Z
        System.out.println(instant6);  //1970-01-01T00:00:05Z
    }
}
ZoneDateTime:带时区的时间

在这里插入图片描述

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class test23 {
    public static void main(String[] args) {
        // 获取当前带时区的时间
        ZonedDateTime zdt=ZonedDateTime.now();
        System.out.println(zdt);  //2024-01-07T13:54:13.668+08:00[Asia/Shanghai]

        // 获取指定时间
        ZonedDateTime zonedDateTime=ZonedDateTime.of(2024,1,7,13,50,33,20, ZoneId.of("Asia/Shanghai"));
        System.out.println(zonedDateTime);  //2024-01-07T13:50:33.000000020+08:00[Asia/Shanghai]

        // 通过Instant+时区获取指定时间
        Instant instant=Instant.ofEpochMilli(1000L);
        ZoneId zoneId=ZoneId.of("Asia/Shanghai");
        ZonedDateTime zonedDateTime10 = instant.atZone(zoneId);
        System.out.println(zonedDateTime10);  //1970-01-01T08:00:01+08:00[Asia/Shanghai]

        // 修改时间
        ZonedDateTime zonedDateTime1 = zonedDateTime.withYear(2019);
        ZonedDateTime zonedDateTime2 = zonedDateTime.withMonth(9);
        ZonedDateTime zonedDateTime3 = zonedDateTime.withDayOfMonth(26);

        System.out.println(zonedDateTime);  //2024-01-07T13:50:33.000000020+08:00[Asia/Shanghai]

        System.out.println(zonedDateTime1);  //2019-01-07T13:50:33.000000020+08:00[Asia/Shanghai]
        System.out.println(zonedDateTime2);  //2024-09-07T13:50:33.000000020+08:00[Asia/Shanghai]
        System.out.println(zonedDateTime3);  //2024-01-26T13:50:33.000000020+08:00[Asia/Shanghai]

        // 减少时间
        ZonedDateTime zonedDateTime4 = zonedDateTime.minusYears(4);
        ZonedDateTime zonedDateTime5 = zonedDateTime.minusMonths(2);
        ZonedDateTime zonedDateTime6 = zonedDateTime.minusDays(4);
        
        System.out.println(zonedDateTime4);  //2020-01-07T13:50:33.000000020+08:00[Asia/Shanghai]
        System.out.println(zonedDateTime5);  //2023-11-07T13:50:33.000000020+08:00[Asia/Shanghai]
        System.out.println(zonedDateTime6);  //2024-01-03T13:50:33.000000020+08:00[Asia/Shanghai]

        // 增加时间
        ZonedDateTime zonedDateTime7 = zonedDateTime.plusYears(10);
        ZonedDateTime zonedDateTime8 = zonedDateTime.plusMonths(4);
        ZonedDateTime zonedDateTime9 = zonedDateTime.plusDays(10);

        System.out.println(zonedDateTime7);  //2034-01-07T13:50:33.000000020+08:00[Asia/Shanghai]
        System.out.println(zonedDateTime8);  //2024-05-07T13:50:33.000000020+08:00[Asia/Shanghai]
        System.out.println(zonedDateTime9);  //2024-01-17T13:50:33.000000020+08:00[Asia/Shanghai]
    }
}

日期格式化类:SimpleDateFormat

DateTimeFormatter:用于时间的格式化和解析

在这里插入图片描述

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class test24 {
    public static void main(String[] args) {
        // 获取格式对象
        DateTimeFormatter stf=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 获取时间对象
        ZonedDateTime zonedDateTime = Instant.now().atZone(ZoneId.of("Asia/Shanghai"));

        // 格式化时间对象
        String format = stf.format(zonedDateTime);
        
        System.out.println(format);  //2024-01-07 14:19:12
    }
}

日历类:Calendar

LocalDate、LocalTime、LocalDateTime方法

在这里插入图片描述

LocalDate、LocalTime、LocalDateTime之间的转换

在这里插入图片描述

import java.time.*;

public class test25 {
    public static void main(String[] args) {

        // LocalDate
        // 获取当前时间
        LocalDate localDate=LocalDate.now();
        System.out.println(localDate);  //2024-01-07

        LocalDateTime localDateTime1 = localDate.atStartOfDay();
        System.out.println(localDateTime1);  //2024-01-07T00:00

        // 获取日历中指定信息
        int year = localDate.getYear();
        Month month = localDate.getMonth();
        int month1=month.getValue();
        int dayOfMonth = localDate.getDayOfMonth();

        System.out.println(year);  //2024
        System.out.println(month);  //JANUARY
        System.out.println(month1);  //1
        System.out.println(dayOfMonth);  //7

        // 比较时间前后
        LocalDate localDate1=LocalDate.of(2022,11,20);
        boolean after = localDate.isAfter(localDate1);
        boolean before = localDate.isBefore(localDate1);

        System.out.println(after);  //true
        System.out.println(before);  //false

        // 修改日历信息
        LocalDate localDate2 = localDate1.withYear(2023);
        LocalDate localDate3 = localDate1.withMonth(12);
        LocalDate localDate4 = localDate1.withDayOfMonth(29);

        System.out.println(localDate2);  //2023-11-20
        System.out.println(localDate3);  //2022-12-20
        System.out.println(localDate4);  //2022-11-29

        // LocalTime
        LocalTime localTime=LocalTime.now();  //14:29:51.394
        LocalTime localTime1 = LocalTime.now(ZoneId.of("America/Cuiaba"));  //02:29:51.394

        System.out.println(localTime);
        System.out.println(localTime1);

        // LocalDateTime
        LocalDateTime localDateTime=LocalDateTime.now();
        LocalDateTime localDateTime5=LocalDateTime.now(ZoneId.of("America/Cuiaba"));

        System.out.println(localDateTime);  //2024-01-07T14:31:12.884
        System.out.println(localDateTime5);  //2024-01-07T02:31:12.884

        // 转换
        LocalDate localDate5 = localDateTime.toLocalDate();
        LocalTime localTime2 = localDateTime.toLocalTime();

        System.out.println(localDate5);  //2024-01-07
        System.out.println(localTime2);  //14:44:20.837
    }
}
判断生日
import java.time.LocalDate;
import java.time.MonthDay;

public class test26 {
    public static void main(String[] args) {
        LocalDate birth=LocalDate.of(2002,11,20);
        LocalDate now=LocalDate.now();

        MonthDay birthMonthDay=MonthDay.of(birth.getMonthValue(),birth.getDayOfMonth());
        MonthDay nowMonthDay=MonthDay.of(now.getMonthValue(),now.getDayOfMonth());
        
        if(birthMonthDay.equals(nowMonthDay)){
            System.out.println("今天生日!");
        }
    }
}

工具类

Duration:时间间隔(秒、纳秒)
import java.time.Duration;
import java.time.LocalTime;

public class test28 {
    public static void main(String[] args) {
        // Duration
        LocalTime now=LocalTime.now();
        LocalTime localTime=LocalTime.of(12,0,0);

        Duration duration=Duration.between(localTime,now);
        System.out.println(duration);  //PT3H4M39.451S
        System.out.println(duration.toDays());  //0
        System.out.println(duration.toHours());  //3
        System.out.println(duration.toMinutes());  //184
        System.out.println(duration.toMillis());  //11079451
        System.out.println(duration.toNanos());  //11079451000000
    }
}
Period:时间间隔(年、月、日)
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;

public class test27 {
    public static void main(String[] args) {
        // Period
        LocalDate now=LocalDate.now();
        LocalDate birth=LocalDate.of(2002,11,20);
        Period period=Period.between(birth,now);  //第二个参数减去第一个参数

        System.out.println(period);  //P21Y1M18D
        System.out.println(period.getYears());  //21
        System.out.println(period.getMonths());  //1
        System.out.println(period.getDays());  //18
        System.out.println(period.toTotalMonths());  //253

    }
}
ChronoUnit:时间间隔(所有单位)
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class test29 {
    public static void main(String[] args) {
        LocalDateTime now=LocalDateTime.now();
        LocalDateTime localDateTime=LocalDateTime.of(2022,11,20,12,54,30);

        System.out.println(ChronoUnit.YEARS.between(localDateTime,now));  //1
        System.out.println(ChronoUnit.MONTHS.between(localDateTime,now));  //13
        System.out.println(ChronoUnit.DAYS.between(localDateTime,now));  //413
        System.out.println(ChronoUnit.HOURS.between(localDateTime,now));  //9914
        System.out.println(ChronoUnit.MINUTES.between(localDateTime,now));  //594855
        System.out.println(ChronoUnit.SECONDS.between(localDateTime,now));  //35691339
    }
}

文章来源:https://blog.csdn.net/m0_62122789/article/details/135440126
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。