JDK8以前的日期时间类
System获取时间戳的方法**public static long currentTimeMillis()**
用来返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差(时间戳)。此方法适于计算时间差
计算世界时间的主要标准有: UTC(Coordinated Universal Time) GMT(Greenwich Mean Time) CST(Central Standard Time)
// 获取系统当前时间:System类中的currentTimeMillis()// 返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差。// 称为时间戳long time = System.currentTimeMillis();System.out.println(time);
Date类
java.util.Date
|—-java.sql.Date
java.util.Date表示特定的瞬间,精确到毫秒
构造器**Date()**根据当前的默认毫秒值创建日期对象**Date(long date)**根据给定的毫秒值创建日期对象
常用方法**long getTime()**获取时间,从Date得到一个毫秒值,以毫秒为单位**public void setTime(long time)**设置时间,把一个毫秒值转换为Date**boolean before(Date when)**测试此时间是否在制定时间之前**boolean after(Date when)**测试此时间是否在制定时间之后**toString()**把此Date对象转换为以下形式的String
- dow mon dd hh:mm:ss zzz yyyy
- 其中:doW是一周中的某一天,zzz是时间标准
java.util.Date类与java.sql.Date类
- 两个构造器的使用
- 构造器一:Date():创建一个对应当前时间的Date对象
- 构造器二:创建指定毫秒数的Date对象
- 两个方法的使用
- toString():显示当前的年、月、日、时、分、秒
- getTime():获取当前Date对象对应的毫秒数。(时间戳)
- java.sql.Date对应着数据库中的日期类型的变量
如何将java.util.Date对象转换为java.sql.Date对象
//构造器一:Date():创建一个对应当前时间的Date对象Date date1 = new Date();System.out.println(date1.toString()); // Sat May 02 16:35:31 GMT+08:00 2020System.out.println(date1.getTime()); // 1550106204104//构造器二:创建指定毫秒数的Date对象Date date2 = new Date(35235325345L);System.out.println(date2.toString());//创建java.sql.Date对象java.sql.Date date3 = new java.sql.Date(35235325345L);System.out.println(date3); // 1971-02-13//如何将java.util.Date对象转换为java.sql.Date对象//情况一:Date date4 = new java.sql.Date(2343243242323L);java.sql.Date date5 = (java.sql.Date) date4;//情况二:Date date6 = new Date();java.sql.Date date7 = new java.sql.Date(date6.getTime());
SimpleDateFormat类
java.text.SimpleDateFormat
Date类的API不易于国际化,大部分被废弃了
java.text.SimpleDateFormat类是一个不与语言环境有关的方式来格式化和解析日期的具体类
格式化:**SimpleDateFormat()**默认的模式和语言环境创建对象 19-6-16 下午8:56**public SimpleDateFormat(String pattern)**用参数pattern指定的格式创建一个对象
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MM.dd GGG hh:mm aaa");

**public String format(Datedate)**方法格式化时间对象date**public Date parse(String source)**从给定字符串的开始解析文本,以生成个日期
public void test2() throws ParseException {// 实例化Date对象Date date1 = new Date();// 实例化SimpleDateFormate对象,并设置显示格式SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:aaa");// 格式化date对象String format = sdf.format(date1);System.out.println(format.toString()); // 2020-09-19 02:09:下午// 解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现),// 否则,抛异常Date date2 = sdf.parse("2020-04-20 14:20:下午");System.out.println(date2.toString()); // Tue Jan 21 02:20:00 CST 2020}
public void test3() throws ParseException {String brith = "1997-10-15";// 新建SimpleDateFormat对象并设置时间格式SimpleDateFormat simpBrith = new SimpleDateFormat("yyyy-mm-dd");// 将字符串格式的时间格式化为Date类Date brithday = simpBrith.parse(brith);// 通过Date的getTime方法将Date对象转化为时间戳放到java.sql.date类的构造方法中java.sql.Date brithDate = new java.sql.Date(brithday.getTime());System.out.println(brithDate);}
Calendar类:日历类、抽象类
Calendar是一个抽象基类,主用用于完成日期字段之间相互操作的功能
- 获取Calenda实例的方法使用
**Calendar.getInstance()**方法调用它的子类 GregorianCalendarl 的构造器 - 一个 Calendar的实例是系统时间的抽象表示,通过 get(int field)方法来取得想要的时间信息
- 注意 获取月份是以0开始的
- 获取星期时:周日是1,周二是2,。。。周六是7
实例化
方式一:创建其子类GregorianCalendar的对象
方式二:调用其静态方法getInstance()
Calendar calendar = new GregorianCalendar();Calendar calendar = new GregorianCalendar(年月日时分秒);Calendar calendar = Calendar.getInstance();
常用方法**public int get(int field)**获取日期**public void set(int field,int value)**设置日期**public void add(int field, int amount)**根据日历的规则,为给定的日历字段添加或减去指定的时间量。(amount可以是负的)**public long getTime()**日历类—>Date**void setTime(Date date)**Date—>日历类
// 1.实例化// 方式一:创建其子类(GregorianCalendar)的对象// 方式二:调用其静态方法getInstance()Calendar calendar = Calendar.getInstance();// System.out.println(calendar.getClass());// 2.常用方法// get()int days = calendar.get(Calendar.DAY_OF_MONTH);System.out.println(days);System.out.println(calendar.get(Calendar.DAY_OF_YEAR));// set()// calendar可变性calendar.set(Calendar.DAY_OF_MONTH, 22);days = calendar.get(Calendar.DAY_OF_MONTH);System.out.println(days);// add()calendar.add(Calendar.DAY_OF_MONTH, -3);days = calendar.get(Calendar.DAY_OF_MONTH);System.out.println(days);// getTime():日历类---> DateDate date = calendar.getTime();System.out.println(date);// setTime():Date ---> 日历类Date date1 = new Date();calendar.setTime(date1);days = calendar.get(Calendar.DAY_OF_MONTH);System.out.println(days);
JDK8中新的日期时间类
日期时间API的迭代
第一代:jdk 1.0 Date类
第二代:jdk 1.1 Calendar类,一定程度上替换Date类
第三代:jdk 1.8 提出了新的一套API
前两代的问题
- 可变性:像日期和时间这样的类应该是不可变的
- 偏移性:Calendar中的年份是从1900开始的,而月份都从0开始
- 格式化:格式化只对Date用,Calendar则不行
- 此外,它们也不是线程安全的;不能处理闰秒等
Java 8.0中新引入的java.time API,纠正了过去的缺陷 Java 8.0吸收了Joda-Time的精华,以一个新的开始为Java创建优秀的APl 新的java.time中包含了所有关于本地日期(LocalDate)、本地时间(Localtime)、本地日期时间(LocalDate time)、时区(ZonedDateTime)和持续时间(Duration)的类。历史悠久的Date类新增了tolnstant()方法用于把Date转换成新的表示形式。这些新增的本地化时间日期API大大简化了日期时间和本地化的管理
时间日期类:LocalDate、LocalTime、LocalDateTime
说明
- 分别表示使用 ISO-8601日历系统的日期、时间、日期和时间。它们提供了简单的本地日期或时间,并不包含当前的时间信息,也不包含与时区相关的信息
- LocalDateTime相较于LocalDate、LocalTime,使用频率要高
- 类似于Calendar
常用方法
@Testpublic void test1() {//now():获取当前的日期、时间、日期+时间LocalDate localDate = LocalDate.now();LocalTime localTime = LocalTime.now();LocalDateTime localDateTime = LocalDateTime.now();System.out.println(localDate);System.out.println(localTime);System.out.println(localDateTime); // 2019-07-09T18:17:22.618//of():设置指定的年、月、日、时、分、秒。没有偏移量LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43);System.out.println(localDateTime1); // 2020-10-06T13:23:43//getXxx():获取相关的属性System.out.println(localDateTime.getDayOfMonth());System.out.println(localDateTime.getDayOfWeek());System.out.println(localDateTime.getMonth()); // JULYSystem.out.println(localDateTime.getMonthValue()); // 7System.out.println(localDateTime.getMinute());//体现不可变性//withXxx():设置相关的属性LocalDate localDate1 = localDate.withDayOfMonth(22);System.out.println(localDate);System.out.println(localDate1);LocalDateTime localDateTime2 = localDateTime.withHour(4);System.out.println(localDateTime);System.out.println(localDateTime2);//不可变性LocalDateTime localDateTime3 = localDateTime.plusMonths(3);System.out.println(localDateTime);System.out.println(localDateTime3);LocalDateTime localDateTime4 = localDateTime.minusDays(6);System.out.println(localDateTime);System.out.println(localDateTime4);}
时间点:Instant
在处理时间和日期的时候,我们通常会想到年,月,日,时,分,秒。然而,这只是时间的一个模型,是面向人类的。第二种通用模型是面向机器的,或者说是连续的。在此模型中,时间线中的一个点表示为一个很大的数,这有利于计算机处理。在UNIX中,这个数从1970年开始,以秒为的单位;同样的,在Java中,也是从1970年开始,但以毫秒为单位 java.time包通过值类型Instant提供机器视图,不提供处理人类意义上的时间单位。Instant表示时间线上的一点,而不需要任何上下文信息,例如,时区。概念上讲,它只是简单的表示自1970年1月1日0时0分0秒(UTC)开始的秒数。因为java.time包是基于纳秒计算的,所以Instant的精度可以达到纳秒级(1 ns = 10-9 s) 1秒 = 1000毫秒 =106微秒=109纳秒
说明
- 时间线上的一个瞬时点。 概念上讲,它只是简单的表示自1970年1月1日0时0分0秒
- 类似于 java.util.Date类
常用方法
public void test2(){// now():获取本初子午线对应的标准时间Instant instant = Instant.now();System.out.println(instant); // 2019-02-18T07:29:41.719Z// 添加时间的偏移量OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));System.out.println(offsetDateTime); // 2019-02-18T15:32:50.611+08:00// toEpochMilli():获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数--->Date类的getTime()long milli = instant.toEpochMilli();System.out.println(milli);// ofEpochMilli():通过给定的毫秒数,获取Instant实例 -->Date(long millis)Instant instant1 = Instant.ofEpochMilli(1550475314878L);System.out.println(instant1);}
日期时间格式化类:DateTimeFormatter
说明
- 格式化或解析日期、时间
- 类似于SimpleDateFormat
常用方法
实例化方式:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
本地化相关的格式。如:ofLocalizedDateTime(FormatStyle.LONG)
自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
特别的:自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
// 方式一:预定义的标准格式// 如:ISO_LOCAL_DATE_TIME; ISO_LOCAL_DATE; ISO_LOCAL_TIMEDateTimeFormatter dtf = DateTimeFormatter.ISO_LOCAL_DATE_TIME;// 格式化:日期-->字符串LocalDateTime localDateTime = LocalDateTime.now();String str1 = dtf.format(localDateTime);System.out.println(localDateTime); // 2019-06-21T19:13:13.530System.out.println(str1); // 2019-06-21T19:13:13.53// 解析:字符串 -->日期TemporalAccessor parse = formatter.parse("2000-04-21T19:13:13.53");System.out.println(parse); // {},ISO resolved to 2000-04-21T19:13:13.530// 方式二:// 本地化相关的格式。如:ofLocalizedDateTime()// FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTimeDateTimeFormatter dtf1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);String str2 = dtf1.format(localDateTime);System.out.println(str2);//2019年6月21日 下午07时16分57秒// 本地化相关的格式。如:ofLocalizedDate()// FormatStyle.FULL/FormatStyle.LONG/FormatStyle.MEDIUM/FormatStyle.SHORT:// 适用于LocalDateDateTimeFormatter dtf2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);String str3 = dtf2.format(LocalDate.now());System.out.println(str3); // 2019-6-21// 🔴方式三:自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");String Str4 = dtf3.format(LocalDateTime.now());System.out.println(Str4); // 2019-06-21 07:24:06TemporalAccessor accessor = dtf3.parse("2019-05-06 08:09:06");System.out.println(accessor);// {SecondOfMinute=9, HourOfAmPm=8, NanoOfSecond=0, MicroOfSecond=0,// MinuteOfHour=9, MilliOfSecond=0},ISO resolved to 2019-05-06
其它API的使用

带时区的日期时间
ZonedDateTime / ZoneId
// ZoneId:类中包含了所的时区信息@Testpublic void test1() {// getAvailableZoneIds():获取所的ZoneIdSet<String> zoneIds = ZoneId.getAvailableZoneIds();for(String s : zoneIds){System.out.println(s);}System.out.println();//获取“Asia/Tokyo”时区对应的时间LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of("Asia/Tokyo"));System.out.println(localDateTime);}//ZonedDateTime:带时区的日期时间@Testpublic void test2(){//now():获取本时区的ZonedDateTime对象ZonedDateTime zonedDateTime = ZonedDateTime.now();System.out.println(zonedDateTime);//now(ZoneId id):获取指定时区的ZonedDateTime对象ZonedDateTime zonedDateTime1 = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));System.out.println(zonedDateTime1);}
时间间隔Duration
用于计算两个“时间”间隔,以秒和纳秒为基准
public void test3(){LocalTime localTime = LocalTime.now();LocalTime localTime1 = LocalTime.of(15, 23, 32);//between():静态方法,返回Duration对象,表示两个时间的间隔Duration duration = Duration.between(localTime1, localTime);System.out.println(duration);System.out.println(duration.getSeconds());System.out.println(duration.getNano());LocalDateTime localDateTime = LocalDateTime.of(2016, 6, 12, 15, 23, 32);LocalDateTime localDateTime1 = LocalDateTime.of(2017, 6, 12, 15, 23, 32);Duration duration1 = Duration.between(localDateTime1, localDateTime);System.out.println(duration1.toDays());}
日期间隔Period
用于计算两个“日期”间隔,以年、月、日衡量
public void test4(){LocalDate localDate = LocalDate.now();LocalDate localDate1 = LocalDate.of(2028, 3, 18);Period period = Period.between(localDate, localDate1);System.out.println(period);System.out.println(period.getYears());System.out.println(period.getMonths());System.out.println(period.getDays());Period period1 = period.withYears(2);System.out.println(period1);}
日期时间校正器:TemporalAdjuster
public void test5(){//获取当前日期的下一个周日是哪天?TemporalAdjuster temporalAdjuster = TemporalAdjusters.next(DayOfWeek.SUNDAY);LocalDateTime localDateTime = LocalDateTime.now().with(temporalAdjuster);System.out.println(localDateTime);//获取下一个工作日是哪天?LocalDate localDate = LocalDate.now().with(new TemporalAdjuster(){@Overridepublic Temporal adjustInto(Temporal temporal) {LocalDate date = (LocalDate)temporal;if(date.getDayOfWeek().equals(DayOfWeek.FRIDAY)){return date.plusDays(3);}else if(date.getDayOfWeek().equals(DayOfWeek.SATURDAY)){return date.plusDays(2);}else{return date.plusDays(1);}}});System.out.println("下一个工作日是:" + localDate);}
新的日期API与原来API的转化问题
