java常用类:日期类Date,Calender和LocalDateTime

java常用类型:
Ineteger等包装类
String类,StringBuffer类和StringBuilder类
Math类及常用方法
System类及常用方法
Arrays类及常用方法
BigInteger类和BigDecimal类及常用方法
日期类Date类,Calender类和LocalDateTime类

引言

第一代和第二代处理时间的方法基本弃用,仅做了解,重点是第三代java8推出的LocalDateTime

日期类

Date(第一代)

在这里插入图片描述

java Date n1 = new Date() //获取系统时间

1.java.util.Data 工具相关

2.java.sql.Data 数据库查询相关(不要引入)

3.格式转换

在这里插入图片描述

时间戳转字符串

在这里插入图片描述

扫描二维码关注公众号,回复: 17274325 查看本文章

用例

在这里插入图片描述

java Date d1 =new Date(); //E 输出日期

字符串转时间

在这里插入图片描述

转时间 需要抛出异常 throws

因为字符串不一定对


Calender(第二代)

简介

在这里插入图片描述

常用方法

在这里插入图片描述

注意事项

  • 没有提供格式控制符 格式控制自由定制

  • 月份+1 ,因为月份从零 开始标记

  • 日期: DAY_OF_MONTH

  • 时 : HOUR

  • 24时 :HOUR_OF_DAY

区别

Calender.get(Calender.HOUR)

Calender.get(Calender.DAY_OF_MON)


LocalDate(第三代 弃用前两代)

前两代缺点

在这里插入图片描述

1.Jdk8加入此方法,也是jdk8的特性之一

LocalDate : 只能操作年月日

LocalTime : 只能操作时分秒

LocalDateTime: 能操作年月日时分秒

2.常用的对象关键词

  • ZoneId: 时区ID,用来确定Instant和LocalDateTime互相转换的规则
  • Instant:用来表示时间线上的一个点(瞬时)
  • LocalDate: 表示没有时区的日期, LocalDate是不可变并且线程安全的
  • LocalTime: 表示没有时区的时间, LocalTime是不可变并且线程安全的
  • LocalDateTime:表示没有时区的日期时间, LocalDateTime是不可变并且线程安全的
  • Clock: 用于访问当前时刻、日期、时间,用到时区
  • Duration: 用秒和纳秒表示时间的数量(长短),用于计算两个日期的“时间”间隔
  • Period: 用于计算两个“日期”间隔

在这里插入图片描述

1、时间的获取与转换

1.1、获取当前时间

LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();

1.2、时间之间的转换

LocalDateTime dt = LocalDateTime.now(); // 当前日期和时间
LocalDate d = dt.toLocalDate(); // 转换到当前日期
LocalTime t = dt.toLocalTime(); // 转换到当前时间

1.3、通过指定的日期和时间创建LocalDateTime,用of

LocalDate d2 = LocalDate.of(2020, 11, 30); // 2019-11-30
LocalTime t2 = LocalTime.of(15, 16, 17); // 15:16:17
LocalDateTime dt2 = LocalDateTime.of(2020, 11, 30, 15, 16, 17);
LocalDateTime dt3 = LocalDateTime.of(d2, t2);

1.4、日期字符串转LocalDateTime

LocalDateTime dt = LocalDateTime.parse("2019-11-19T15:16:17");
LocalDate d = LocalDate.parse("2019-11-19");
LocalTime t = LocalTime.parse("15:16:17");

注意:ISO 8601规定的日期和时间分隔符是T。标准格式如下:

日期:yyyy-MM-dd
时间:HH:mm:ss
带毫秒的时间:HH:mm:ss.SSS
日期和时间:yyyy-MM-dd'T'HH:mm:ss
带毫秒的日期和时间:yyyy-MM-dd'T'HH:mm:ss.SSS

延伸:
DateTimeFormatter

如果要自定义输出的格式,或者要把一个非ISO 8601格式的字符串解析成LocalDateTime,可以使用新的DateTimeFormatter:

import java.time.*;
import java.time.format.*;
 
 
public class Main {
    
    
    public static void main(String[] args) {
    
    
        // 自定义格式化:
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        System.out.println(dtf.format(LocalDateTime.now()));
 
        // 用自定义格式解析:
        LocalDateTime dt2 = LocalDateTime.parse("2020/10/20 15:16:17", dtf);
        System.out.println(dt2);
    }
}

2、日期时间的加减

LocalDateTime

2.1、提供了对日期和时间进行加减的非常简单的链式调用:

对于LocalDate,只有精度大于或等于日的加减,如年、月、日;
对于LocalTime,只有精度小于或等于时的加减,如时、分、秒、纳秒;
对于LocalDateTime,则可以进行任意精度的时间相加减;

LocalDateTime localDateTime = LocalDateTime.now();
//以下方法的参数都是long型,返回值都是LocalDateTime
LocalDateTime plusYearsResult = localDateTime.plusYears(2L);
LocalDateTime plusMonthsResult = localDateTime.plusMonths(3L);
LocalDateTime plusDaysResult = localDateTime.plusDays(7L);
LocalDateTime plusHoursResult = localDateTime.plusHours(2L);
LocalDateTime plusMinutesResult = localDateTime.plusMinutes(10L);
LocalDateTime plusSecondsResult = localDateTime.plusSeconds(10L);
 
 
//也可以以另一种方式来相加减日期,即plus(long amountToAdd, TemporalUnit unit)
//                  参数1 : 相加的数量, 参数2 : 相加的单位
LocalDateTime nextMonth = localDateTime.plus(1, ChronoUnit.MONTHS);
LocalDateTime nextYear = localDateTime.plus(1, ChronoUnit.YEARS);
LocalDateTime nextWeek = localDateTime.plus(1, ChronoUnit.WEEKS);

2.2、将年、月、日等修改为指定的值,并返回新的日期(时间)对象

以下列出 LoalDateLocalDateTime  对应的使用方法,LocalDateTime拥有以下所有方法)

    LocalDate localDate = LocalDate.now();
    //当前时间基础上,指定本年当中的第几天,取值范围为1-365,366
    LocalDate withDayOfYearResult = localDate.withDayOfYear(200);
    //当前时间基础上,指定本月当中的第几天,取值范围为1-29,30,31
    LocalDate withDayOfMonthResult = localDate.withDayOfMonth(5);
    //当前时间基础上,直接指定年份
    LocalDate withYearResult = localDate.withYear(2017);
    //当前时间基础上,直接指定月份
    LocalDate withMonthResult = localDate.withMonth(5);
     
     
    LocalTime localTime = LocalTime.now();
    //当前时间基础上,直接指定小时
    LocalTime withHourResult = localTime.withHour(1);
    //当前时间基础上,直接指定分钟
    LocalTime withMinuteResult = localTime.withMinute(15);
    //当前时间基础上,直接指定秒
    LocalTime withSecondResult = localTime.withSecond(20);

注意:调整月份时,会相应地调整日期,即把2019-10-31的月份调整为9时,日期也自动变为30

延伸:LocalDateTime还有一个通用的with()方法允许我们做更复杂的运算:

// 本月第一天0:00时刻:
LocalDateTime firstDay = LocalDate.now().withDayOfMonth(1).atStartOfDay();
 
// 本月最后1天:
LocalDate lastDay = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
 
// 下月第1天:
LocalDate nextMonthFirstDay = LocalDate.now().with(TemporalAdjusters.firstDayOfNextMonth());
 
// 本月第1个周一:
LocalDate firstWeekday = LocalDate.now().with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));

2.3、获取日期的年月日周时分秒


  LocalDateTime localDateTime = LocalDateTime.now();
    int dayOfYear = localDateTime.getDayOfYear();
    int dayOfMonth = localDateTime.getDayOfMonth();
    DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
     
    System.out.println("今天是" + localDateTime + "\n"
            + "本年当中第" + dayOfYear + "天" + "\n"
            + "本月当中第" + dayOfMonth + "天" + "\n"
            + "本周中星期" + dayOfWeek.getValue() + "-即" + dayOfWeek + "\n");
     
            
    //获取当天时间的年月日时分秒
    int year = localDateTime.getYear();
    Month month = localDateTime.getMonth();
    int day = localDateTime.getDayOfMonth();
    int hour = localDateTime.getHour();
    int minute = localDateTime.getMinute();
    int second = localDateTime.getSecond();
    System.out.println("今天是" + localDateTime + "\n"
            + "年 : " + year + "\n"
            + "月 : " + month.getValue() + "-即 "+ month + "\n"
            + "日 : " + day + "\n"
            + "时 : " + hour + "\n"
            + "分 : " + minute + "\n"
            + "秒 : " + second + "\n"
            );

2.4、时间日期前后的比较与判断

要判断两个LocalDateTime的先后,可以使用isBefore()、isAfter()方法,对于LocalDate和LocalTime类似

//判断两个时间点的前后
LocalDateTime now = LocalDateTime.now();
LocalDateTime target = LocalDateTime.of(2019, 11, 19, 8, 15, 0);
System.out.println(now.isBefore(target));
System.out.println(LocalDate.now().isBefore(LocalDate.of(2019, 11, 19)));
System.out.println(LocalTime.now().isAfter(LocalTime.parse("08:15:00")));

注意:LocalDateTime无法与时间戳进行转换,因为LocalDateTime没有时区,无法确定某一时刻。ZonedDateTime相当于LocalDateTime加时区的组合,它具有时区,可以与long表示的时间戳进行转换。

2.5、时间、日期间隔的计算

2.5.1、Period:用于计算两个“日期”间隔

//计算两个日期的日期间隔-年月日
LocalDate date1 = LocalDate.of(2020, 10, 21);
LocalDate date2 = LocalDate.of(2019, 9, 11);
//内部是用date2-date1,所以得到的结果是负数
Period period = Period.between(date1, date2);
System.out.println("相差年数 : " + period.getYears());
System.out.println("相差月数 : " + period.getMonths());
System.out.println("相差日数 : " + period.getDays());
//另一种计算方式和表现形式
System.out.println("-------------------------------");
long years = period.get(ChronoUnit.YEARS);
long months = period.get(ChronoUnit.MONTHS);
long days = period.get(ChronoUnit.DAYS);
System.out.println("相差的年月日分别为 : " + years + "," + months + "," + days);

注意:当获取两个日期的间隔时,并不是单纯的年月日对应的数字相加减,而是会先算出具体差多少天,在折算成相差几年几月几日的

2.5.2、Duration:用于计算两个“时间”间隔

 //计算两个时间的间隔
    System.out.println("-------------------------------");
    LocalDateTime date3 = LocalDateTime.now();
    LocalDateTime date4 = LocalDateTime.of(2018, 1, 13, 22, 30, 10);
    Duration duration = Duration.between(date3, date4);
    System.out.println(date3 + " 与 " + date4 + " 间隔  " + "\n"
            + " 天 :" + duration.toDays() + "\n"
            + " 时 :" + duration.toHours() + "\n"
            + " 分 :" + duration.toMinutes() + "\n"
            + " 毫秒 :" + duration.toMillis() + "\n"
            + " 纳秒 :" + duration.toNanos() + "\n"
            );

注意:并没有获得秒差,没有该方法,不过可以通过毫秒换算

猜你喜欢

转载自blog.csdn.net/imbzz/article/details/128835680