文章目录
一、JDK1.7之前的时间表示缺点
- 非线程安全:java.util.Date是非线程安全的。
- 设计差:Date类在java.util包和java.sql包中都有,区分性差。
- 时间格式化和解析的类在java.text包中定义,而时间类在java.util包中定义。
- java.util.Date同时包含日期和时间,而java.sql.Date仅包含日期。
- 时区处理麻烦:日期类不提供国际化,没时区支持。
二、java8中time类
两个比较重要的API
- Local(本地):简化了时间日期的处理,没有时区问题。
- Zoned(时区):通过制定的时区处理日期时间。
三、LocalDateTime类、LocalDate类、LocalTime类
3.1 获取当前时间
public void test()
{
//获取当前日期时间
LocalDateTime currenttime = LocalDateTime.now();
System.out.println("当前时间:"+currenttime);
}
输出:
当前时间:2020-12-30T11:48:12.732
3.2 获取当前日期
//获取当前的日期
LocalDate date0 = LocalDate.now();
System.out.println("date0"+date0);
LocalDate date1 = currenttime.toLocalDate();
System.out.println("date1"+date1);
输出:
date02020-12-30
date12020-12-30
3.3 获取年月日时分秒
//获取年月日时分秒
Month month = currenttime.getMonth();
int day = currenttime.getDayOfMonth();
int seconds = currenttime.getSecond();
System.out.println("月:"+month+",日:"+day+",秒:"+seconds);
结果:
月:DECEMBER,日:30,秒:6
3.4 设定年月日时分秒
//设定年月日时分秒
LocalDateTime date2 = currenttime.withDayOfMonth(10).withYear(20);
System.out.println("date2:"+date2);
结果:
date2:0020-12-10T13:44:58.166
3.5 设定日期
//设定日期12 december 2014
LocalDate date3 = LocalDate.of(2014, Month.DECEMBER, 15);
System.out.println("date3:"+date3);
结果:
date3:2014-12-15
3.6 设定时间
//设定时间 23 小时59分钟
LocalTime time = LocalTime.of(23, 59);
System.out.println("time:"+time);
结果:
time:23:59
3.6 字符串转化为时间
3.6.1 parse(CharSequence text)方法
用法:
public static LocalTime parse(CharSequence text)
参数:此方法仅接受一个参数文本,该参数文本是在LocalTime中解析的文本。它不能为空。
返回值:此方法返回LocalTime,它是解析的本地日期时间。
异常:如果无法解析文本,则此方法将引发DateTimeParseException。
示例:
//类型转换:解析字符串
LocalTime time1 = LocalTime.parse("20:15:36");
System.out.println("time1:"+time1);
结果:
time1:20:15:36
3.6.2 parse(CharSequence text, DateTimeFormatter formatter)方法
用法:
public static LocalTime parse(CharSequence text, DateTimeFormatter formatter)
参数:此方法接受两个参数text(即要解析的文本)和formatter(要使用的格式化程序)。
返回值:此方法返回LocalTime,它是解析的本地日期时间。
异常:如果无法解析文本,则此方法将引发DateTimeParseException。
示例:
LocalTime time2 = LocalTime.parse("10-10-10", DateTimeFormatter.ofPattern("HH-mm-ss"));
System.out.println("time2:"+time2);
结果:
time2:10:10:10
3.7 时间转化为字符串
//时间转化为字符串
LocalTime time3= LocalTime.parse("11-15-36", DateTimeFormatter.ofPattern("HH-mm-ss"));
System.out.println("time3:"+time3.format(DateTimeFormatter.ofPattern("HH@mm@ss")));
结果:
time3:11@15@36
DateTimeFormatter.ofPattern("HH-mm-ss")
中HH、mm、ss不能变,保证准确。