日期时间API
java.util.Date类
1.两个构造器的使用
- 构造器一:Date():创建了一个对应当前时间的Date对象
//构造器一:Date():创建了一个对应当前时间的Date对象
Date date1 = new Date();
System.out.println(date1.toString());
System.out.println(date1.getTime());
- 构造器二:创建指定毫秒数的Date对象
//构造器二:创建指定毫秒数的Date对象
Date date2 = new Date(1550306204104L);
System.out.println(date2);
2.两个方法的使用
- toString():显示当前的年月日时分秒
- getTime():获取当前Date对象对应的毫秒数。(时间戳)
java.sql.Date类
是java.util.Date类的子类
如何将java.util.Date对象转换为java.sql.Date对象
//如何将java.util.Date对象转换为java.sql.Date对象
//情况一:
//Date date4 = new java.sql.Date(216132131613L);
//java.sql.Date date5=(java.sql.Date)date4;
//情况二:
Date date6=new Date();
java.sql.Date date7=new java.sql.Date(date6.getTime());
}
java.lang.System类
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()
long time=System.currentTimeMillis();
//返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差
//称为时间戳
System.out.println(time);
java.text.SimpleDateFormat类
- Date类的API不易于国际化,大部分被废弃了,java.text.SimpleDateFormat类是一个不与语言环境有关的方式来格式化和解析日期的具体类
- 它允许进行格式化:日期->文本,解析:文本->日期
- 格式化:
SimpleDateformat(): 默认的模式和语言环境创建对象
public SimpleDateFormat(String pattern): 该构造方法可以用参数pattern指定的格式创建一个对象,该对象调用
public String format(Date date): 方法格式化时间对象date - 解析:
- public Date parse(String source): 从给定字符串的开始解析文本,以生成一个日期
/*
* SimpleDateFormat的使用:SimpleDateFormat对日期Date类的格式化和解析
* 1.两个操作
* 格式化:日期--->字符串
* 解析:格式化的逆过程,字符串--->日期
* */
@Test
public void testSimpleDateFormat() throws ParseException {
//实例化SimpleDateFormat
SimpleDateFormat sdf=new SimpleDateFormat();
//格式化:日期--->字符串
Date date=new Date();
//System.out.println(date);
String format = sdf.format(date);
System.out.println(format);
//解析:格式化的逆过程,字符串--->日期
String str="19-12-18 下午15:24";
Date parse = sdf.parse(str);
System.out.println(parse);
//********按照指定的方式格式化和解析:调用带参的构造器***********
//SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MMMM.dd GGG hh:mm aaa");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//格式化
String format1 = sdf1.format(date);
System.out.println(format1);//2020-11-01 10:43:33
//解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数实现)
//否则,抛异常
Date parse1 = sdf1.parse("2020-02-18 11:48:27");
System.out.println(parse1);
}
//练习一:字符串"2020-09-08"转换为java.sql.Date
@Test
public void testExer() throws ParseException {
String birth="2020-09-08";
SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
Date parse = sdf1.parse(birth);
//System.out.println(date);
java.sql.Date birthDate = new java.sql.Date(parse.getTime());
System.out.println(birthDate);
}
/*
* 练习二:"三天打渔两天晒网" 1990-01-01 xxxx-xx-xx 打渔? 晒网?
* 举例:2020-09-08 ? 总天数
* 总天数 % 5 == 1,2,3:打渔
* 总天数 % 5 == 4,0:晒网
*
* 总天数的计算?
* 方式一:(date2.getTime()-date1.getTime())/(1000*60*60*24)+1
* 方式二:1990-01-01 --->2019-12-31 + 2020-01-01 -->2020-09-08
* */
@Test
public void testExer1() throws ParseException {
String date1="1990-01-01";
String date2="1990-01-08";
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date parse = sdf.parse(date1);
Date parse1 = sdf.parse(date2);
int time =(int) parse.getTime();
int time1 =(int) parse1.getTime();
int l = (time1 - time) / (1000 * 60 * 60 * 24);
System.out.println(l);
int i = l % 5;
switch (i){
case 0:
System.out.println("晒网");
break;
case 1:
System.out.println("打渔");
break;
case 2:
System.out.println("打渔");
break;
case 3:
System.out.println("打渔");
break;
case 4:
System.out.println("晒网");
break;
default:
break;
}
}
java.util.Calendar类
- Calendar是一个抽象基类,主要用于完成日期字段之间相互操作的功能
- 获取Calendar实例的方法
使用Calendar.getInstance() 方法
调用它的子类GregorianCalendar 的构造器 - 一个Calendar的实例是系统时间的抽象表示,通过get(int field) 方法来取得想要的时间信息。比如YEAR,MONTH,DAY_OF_WEEK,HOUR_OF_DAY,MINUTE,SECOND
public void set(int field,int value)
public void add(int field,int amount)
public final Date getTime()
public final void setTime(Date date) - 注意:
获取月份时:一月是0,二月是1,以此类推,12月是11
获取星期时:周日是1,周二是2,。。。周六是7
/*
* Calendar日历类(抽象类)的使用
*
* */
@Test
public void test() {
//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():日历类--->Date
Date 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
新时间日期API
- java.time 包含值对象的基础包
- java.time.chrono 提供对不同的日历系统的访问
- java.time.format 格式化和解析时间日期
- java.time.temporal 包括底层框架和扩展特性
- java.time.zone 包含时区支持的类
LocalDate,LocalTime,LocalDateTime
LocalDate,LocalTime,LocalDateTime类是其中较重要的几个类,它们的实例是不可变的对象,分别表示使用ISO-8601日历系统的日期,时间,日期和时间。它们提供了简单的本地日期或时间,并不包含当前的时间信息,也不包含与时区相关的信息。
- LocalDate代表IOS格式(yyyy-MM-dd)的日期,可以存储生日,纪念日等日期。
- LocalTime表示一个时间,而不是日期。
- LocalDateTime是用来表示日期和时间的,这是一个最常用的类之一。
方法 | 描述 |
---|---|
now()/* now(ZoneId zone) | 静态方法,根据当前日期创建对象/指定时区的对象 |
of() | 静态方法,根据指定日期/时间创建对象 |
getDayOfMonth()/getDayOfYear() | 获取月份天数(1-31)/获取年份天数(1-366) |
getDayOfWeek() | 获得星期几(返回一个DayOfWeek枚举值 |
getMonth() | 获得月份,返回一个Month枚举值 |
getMonthValue() /getYear() | 获得月份(1-12)/获得年份 |
getHour()/getMinute()/getSecond() | 获得当前对象对应的小时,分钟,秒 |
withDayOfMonth()/withDayOfYear()/withMonth()/withYear() | 将月份天数,年份天数,月份,年份修改为指定的值并返回新的对象 |
plusDays(),plusWeeks(),plusMonths(),plusYears(),plusHours() | 向当前对象添加几天,几周,几个月,几年,几小时 |
minusMonths()/minusWeeks()/minusDays()/minusYears()/minusHours() | 从当前对象减去几天,几周,几个月,几年,几小时 |
/*
* jdk 8中日期时间API的测试
* */
@Test
public void testDate(){
//偏移量
Date date = new Date(2020-1900, 9-1, 8);
System.out.println(date);
}
/*
* LocalDate,LocalTime,LocalDateTime的使用
*
* 1.LocalDateTime相较于LocalDate,LocalTime,使用频率要高
* 2.类似于Calendar
* */
@Test
public void test(){
//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);
//of():设置指定的年,月,日,时,分,秒是没有偏移量的
LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43);
System.out.println(localDateTime1);
//getXxx():获取相关的属性
System.out.println(localDateTime.getDayOfMonth());
System.out.println(localDateTime.getDayOfWeek());
System.out.println(localDateTime.getMonth());
System.out.println(localDateTime.getMonthValue());
System.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);
//不可变性
//plusXxx():增加时间
LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
System.out.println(localDateTime);
System.out.println(localDateTime3);
//不可变性
//minusXxx():减少时间
LocalDateTime localDateTime4 = localDateTime.minusDays(6);
System.out.println(localDateTime);
System.out.println(localDateTime4);
}
瞬时:Instant
- Instant:时间线上的一个瞬时点。这可能被用来记录应用程序中的事件时间戳。
- 种子处理时间和日期的时候,我们通常会想到年月日时分秒。然而,这只是时间的一个模型,是面向人类的。第二种通用模型是目暗巷机器的,或者说是连续的。在此模型中,时间线中的一个点表示为一个很大的数,这有利于计算机处理。在UNIX中,这个数从1970年开始,以秒为单位;同样的,在Java中也是从1970年开始,但以毫秒为单位。
- java.time包通过值类型Instant提供机器视图,不提供处理人类意义上的时间单位。Instant表示时间线上的一点,而不需要任何上下文信息,例如,时区.概念上讲,他只是简单的表示自1970年1月1日0时0分0秒(UTC)开始的毫秒数。因为java.time包是基于纳秒计算的,所以Instant的精度可以达到纳秒级。
- (1 ns=10-9s) 1秒 = 1000毫秒 = 106微秒=109纳秒
方法 | 描述 |
---|---|
now() | 静态方法,返回默认UTC时区的Instant类的对象 |
ofEpochMilli(long epochMilli) | 静态方法,返回在1970-01-01 00:00:00基础上加上指定毫秒数之后的Instant类的对象 |
atOffset(ZoneOffset offset) | 结合即时的偏移来创建一个OffsetDateTime |
toEpochMilli() | 返回1970-01-01 00:00:00到当前时间的毫秒数,即为时间戳 |
时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数
/*
* Instant的使用
* 类似于java.util.Date类
* */
@Test
public void test(){
//now():获取本初子午线对应的标准时间
Instant instant = Instant.now();
System.out.println(instant);
//添加时间的偏移量
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);
//获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数
long milli = instant.toEpochMilli();
System.out.println(milli);
//ofEpochMilli():通过给定的毫秒数,获取Instant实例 --->Date类的getTime()
Instant instant1 = Instant.ofEpochMilli(1604332177889L);
System.out.println(instant1);
}
java.time.format.DateTimeFormatter类
格式化与解析日期或时间,该类提供了三种格式化方法:
- 预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
- 本地化相关的格式。如:ofLocalizedDateTime(FormatStyle.LONG)
- 自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss E”)
方法 | 描述 |
---|---|
ofPattern(String pattern) | 静态方法,返回一个指定字符串格式的DateTimeFormatter |
format(TemporalAccessor t) | 格式化一个日期,时间,返回字符串 |
parse(CharSequence text) | 将指定格式的字符序列解析为一个日期,时间 |
/*
* java.time.format.DateTimeFormatter:格式化与解析日期或时间
* 类似于SimpleDateFormat
* */
@Test
public void test3(){
//方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
//格式化:日期--->字符串
LocalDateTime localDateTime = LocalDateTime.now();
String str1 = formatter.format(localDateTime);
System.out.println(localDateTime);
System.out.println(str1);
//解析:字符串--->日期
TemporalAccessor parse = formatter.parse("2020-11-03T10:28:15.437");
System.out.println(parse);
//方式二:本地化相关的格式。如:ofLocalizedDateTime()
//FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT:适用于LocalDateTime
DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
//格式化
String str2 = formatter1.format(localDateTime);
System.out.println(str2);
//本地化相关的格式。如:ofLocalizedDate()
//FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT:适用于LocalDate
DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
//格式化
String str3 = formatter2.format(LocalDate.now());
System.out.println(str3);
//方式三:自定义的格式。如:ofPattern("yyyy-MM-dd hh:mm:ss E")
DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
String str4 = formatter3.format(LocalDateTime.now());
System.out.println(str4);
//解析
TemporalAccessor accessor = formatter3.parse("2020-11-03 10:40:21");
System.out.println(accessor);
}
其它API
- ZoneId: 该类中包含了所有的时区信息,一个时区的ID,如Europe/Paris
- ZonedDateTime: 一个在ISO-8601日历系统时区的日期时间,如2007-12-03T10:15:30+01:00 Europe/Paris
其中每个时区都对应着ID,地区ID都为"{区域}/{城市}"的格式,例如:Asia/Shanghai等 - Clock: 使用时区提供对当前即时,日期和时间的访问的时钟
- 持续时间:Duration 用于计算两个时间间隔
- 日期间隔:Period用于计算两个日期间隔
- TemporalAdjuster: 时间校正器。有时我们可能需要获取例如:将日期调整到"下一个工作日"等操作
- TemporalAdjusters: 该类通过静态方法(firstDayOfXxx()/lastDayOfXxx()/nextXxx())提供了大量的常用TemporalAdjuster的实现
与传统日期处理的转换
类 | To遗留类 | From遗留类 |
---|---|---|
java.time.Instant与java.util.Date | Date.from(instant) | Data.toInstant |
java.time.Instant与java.sql.Timestamp | Timestamp.from(instant) | timestamp.toInstant() |
java.time.ZonedDateTime与java.util.GregorianCalendar | GregorianCalendar.from(zonedDateTime) | cal.toZonedDateTime() |
java.time.LocalDate与java.sql.Time | Date.valueOf(localDate) | date.toLocalDate() |
java.time.LocalTime与java.sql.Time | Date valueOf(localDate) | date.toLocalTime() |
java.time.LocalDateTime与java.time.Timestamp | Timestamp.valueOf(localDateTime) | timestamp toLocalDateTime() |
java.time.ZoneId与java.util.TimeZone | Timezone getTimeZone(id) | timeZone.toZoneId() |
java.time.format.DateTimeFormatter与java.text.DateFormat | formatter.toFormat() | 无 |