史上最全日期时间类讲解

SimpleDateFormat的基本使用

SimpleDateFormat formats = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//时间类型转为String类型 Date date = new Date(System.currentTimeMillis()); String dateString = formats.format(date); System.out.println("dataString----"+dateString);
//String类型转为时间类型 String time="2021-07-07 15:49:42"; Date date1 = formats.parse(time); System.out.println("Date----"+date1);
//时间类型转成时间戳 Long timeStamp=date1.getTime(); System.out.println("timeStamp----"+timeStamp);

输出结果:dataString----2021-07-07 16:10:08

     Date----Wed Jul 07 15:49:42 CST 2021

     timeStamp----1625644182000

注意 :yyyy-MM-dd HH:mm:ss是时间格式 可修改,比如yyyy-MM-dd;HH:mm:ss;yyyyMMddHHmmss等

           new Date()方法中参数是long类型的毫秒值

栗子:获取现在小时

public static String getHour() {
   Date currentTime = new Date();
   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   String dateString = formatter.format(currentTime);
   String hour;
   hour = dateString.substring(11, 13);
   return hour;
}

栗子: 获取两个日期的间隔天数 getTwoDay("2021-07-08","2021-06-20")

public static String getTwoDay(String day1, String day2) {
   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
   long day = 0;
   try {
      java.util.Date bigDate = format.parse(day1);
      java.util.Date smallDate = format.parse(day2);
      day = (bigDate.getTime() - smallDate.getTime()) / (24 * 60 * 60 * 1000);
    } catch (Exception e) {
      return "";
   }
   return day + "";
}

Calendar 的基本使用

获取当前时间的年月日时分秒

Calendar cal = Calendar.getInstance();
System.out.println("年:" + cal.get(Calendar.YEAR));
System.out.println("月:" + (cal.get(Calendar.MONTH) + 1));
System.out.println("日:" + cal.get(Calendar.DAY_OF_MONTH));
System.out.println("时:" + cal.get(Calendar.HOUR_OF_DAY));
System.out.println("分:" + cal.get(Calendar.MINUTE));
System.out.println("秒:" + cal.get(Calendar.SECOND));

输出结果:年:2021  月:7  日:7  时:16  分:57  秒:53

注意:月份下标从0开始,所以取月份要+1

栗子:1 月 31 号的时候,月份加一,会出现怎样结果:

Calendar cal = Calendar.getInstance();
cal.set(2018, 0, 31, 8, 0, 0);
cal.add(Calendar.MONTH, 1);
System.out.println(cal.getTime());

输出结果:Wed Feb 28 08:00:00 CST 2018

注意:Calendar类的getTime()获取当前日期: Wed Feb 28 08:00:00 CST 2018

LocalDateTime,LocalDate,LocalTime的基本使用

LocalDateTime表示日期和时间,LocalDate用来表示日期,LocalTIme表示时间,LocalDateTime = LocalDate + LocalTIme。

System.out.println(LocalDate.now()); //2020-04-02
System.out.println(LocalTime.now()); //11:29:52.206
System.out.println(LocalDateTime.now()); //2020-04-02T11:29:52.206

1、初始化

LocalDateTime可以分别获取LocalDate和LocalTime:

  1.toLocalDate 返回LocalDateTime的LocalDate部分

  2.toLocalTime 返回LocalDateTime的LocalTime部分

2、获取指定时间

LocalTime.of(int hour,int minute,int second):指定时、分、秒,参数不可缺省

LocalDate.of(int year,MOUTH mouth,int day)

LocalDate.of(int year,int mouth,int day):指定年、月、日,参数不可缺省

这里指定月份的话是从1开始,与Calendar不同,Calendar的月份是从0开始,这也就是LocalDate比Calendar处理时间要方便的多。

LocalDateTime.of(LocalDate localDate,LocalTime localTime)

LocalDateTime.of(nt year,int mouth,int day,int hour,int minute,int second,int nanoOfSecond):指定年、月、日、时、分、秒、纳秒,参数可缺省

//2020-12-01
System.out.println(LocalDate.of(2020,12,1)); 
2020-04-23
System.out.println(LocalDate.of(2020, Month.APRIL,23));
12:23:33
System.out.println(LocalTime.of(12,23,33));
//2020-04-02T11:48:20.785
System.out.println(LocalDateTime.of(LocalDate.now(),LocalTime.now()));
//2322-12-22T23:12:33.000000232
System.out.println(LocalDateTime.of(2322,12,22,23,12,33,232));
//2322-07-22T23:12:33.000000232
System.out.println(LocalDateTime.of(2322,Month.JULY,22,23,12,33,232));

3、时间操作

这里以LocalDateTime进行举例说明

说明:1、plus是增加相应时间单位的水量,minus是减少相应时间单位的数量,此处不再说明;

           2、表中的拷贝实际就是对相应时间位置的数值进行修改

LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        System.out.println(now.plusYears(1)
                .plusMonths(1L)
                .plusWeeks(1)
                .plusDays(1)
                .plusHours(1)
                .plusMinutes(1)
                .plusSeconds(1)
                .plusNanos(500000L));
 
//2020-04-02T12:04:22.507
//2021-05-10T13:05:23.507500
 
LocalDate date = LocalDate.of(2020, 2, 22); // 2020-02-22
LocalDate date1 = date.withYear(2021); // 修改为 2021-02-22
LocalDate date2 = date.withMonth(3); // 修改为 2020-03-22 
LocalDate date3 = date.withDayOfMonth(1); // 修改为 2020-02-01

4、获取时间属性值

5.时间格式之间相互转换

LocalDateTime与String
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒SSS毫秒");
LocalDateTime localDateTime = LocalDateTime.now();
String dateStr = dateTimeFormatter.format(localDateTime);
System.out.println(dateStr); \\2020年04月02日 14时11分01秒623毫秒
LocalDateTime localDateTime2 = LocalDateTime.parse(dateStr, dateTimeFormatter); System.out.println(localDateTime2); \\ 2020-04-02T14:11:01.623
LocalDate localDate = LocalDate.parse(dateStr, dateTimeFormatter); System.out.println(localDate); \\2020-04-02
LocalTime localTime = LocalTime.parse(dateStr, dateTimeFormatter); System.out.println(localTime); \\14:11:01.623
时间戳与LocalDate、LocalDateTime之间相互转换
long timestamp = Instant.now().toEpochMilli();
LocalDateTime localDateTime = Instant.ofEpochMilli(timestamp).atOffset(ZoneOffset.ofHours(8)).toLocalDateTime();
System.out.println(timestamp +"====>"+ localDateTime );
timestamp = localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli(); System.out.println(localDateTime +"====>"+ timestamp );
// 注意秒和毫秒之间的区别 timestamp = LocalDateTime.now().atZone(ZoneOffset.ofHours(8)).toEpochSecond(); localDateTime = Instant.ofEpochSecond(timestamp).atOffset(ZoneOffset.ofHours(8)).toLocalDateTime(); System.out.println(timestamp +"====>"+ localDateTime );
Date与LocalDate、LocalDateTime之间相互转换
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);
Date date = Date.from(localDateTime.atZone(ZoneOffset.ofHours(8)).toInstant()); localDateTime = date.toInstant().atZone(ZoneOffset.ofHours(8)).toLocalDateTime(); System.out.println(date + "======>" + localDateTime); //2020-04-02T14:27:40.230 //Thu Apr 02 14:27:40 CST 2020======>2020-04-02T14:27:40.230

6.其他方法

LocalDateTime now = LocalDateTime.now();
System.out.println("当前时间:" + now);
LocalDateTime from = LocalDateTime.of(2020, 4, 1, 0, 0, 0, 0);
System.out.println(from.until(now, ChronoUnit.HOURS));
/*打印结果:
当前时间:2020-04-03T14:40:39.048
62
*/
 
LocalDateTime date = LocalDateTime.parse("2014-12-03T10:15:30");
System.out.printf("LocalDateTime precision is %s%n",
zonedDateTime.query(TemporalQueries.precision()));
/*打印结果:
LocalDateTime precision is Nanos
*/
ZonedDateTime date = ZonedDateTime.now();
System.out.println(date);
LocalTime standard = LocalTime.parse("10:30:30");
date = (ZonedDateTime)standard.adjustInto(date);
System.out.println(date);
/*打印结果:
2020-04-03T15:03:31.579+08:00[Asia/Shanghai]
2020-04-03T10:30:30+08:00[Asia/Shanghai]
*/

7.Instant(时间点)

  Instant是时间线上的一个点,表示一个时间戳。Instant可以精确到纳秒,这超过了long的最大表示范围,所以在Instant的实现中是分成了两部分来表示,一部分是seconds,表示从1970-01-01 00:00:00开始到现在的秒数,另一个部分是nanos,表示纳秒部分。以下是创建Instant的两种方法:

Instant now = Instant.now(); 
//获取当前时刻的时间戳,结果为:2020-04-02T07:30:23.811Z;
Instant instant = Instant.ofEpochSecond(600, 1000000);
//ofEpochSecond()方法的第一个参数为秒,第二个参数为纳秒,上面的代码表示从1970-01-01 00:00:00开始后一分钟的10万纳秒的时刻,
//其结果为:1970-01-01T00:10:00.001Z。

 

posted @ 2020-10-09 22:54  江南大才子  阅读(504)  评论(0编辑  收藏  举报