1. java8中新的日期时间类
参考文献:Java 8中处理日期和时间示例
Java 8时间和日期API 20例
跟上Java8 - 日期和时间实用技巧
java8以前java.util.date参考:java.util.date
1. java8
中的java.time
及格式化
在java8
中,java.time
包下主要包含下面几个主要的类:
Instant:时间戳
Duration:持续时间,时间差
LocalDate:只包含日期,比如:2016-10-20
LocalTime:只包含时间,比如:23:12:10
LocalDateTime:包含日期和时间,比如:2016-10-20 23:14:21
Period:时间段
ZoneOffset:时区偏移量,比如:+8:00
ZonedDateTime:带时区的时间
Clock:时钟,比如获取目前美国纽约的时间
以及java.time.format
包中的
DateTimeFormatter:时间格式化
如:
1.时间格式化成指定格式的字符串:
LocalDateTime timeNow = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd hh:mm:ss");
System.out.println("时间格式化成成指定格式:"+formatter.format(timeNow));
2.字符串格式化成时间类型:
String iVDate = formatVDate(vDate);
//HH表示24小时制,hh表示12小时制
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDate = LocalDateTime.parse(iVDate, formatter);
2. 比较java.util.date
1.时间格式化成指定格式的字符串:
//1.将Date类型转化成对应格式的字符串
//SimpleDateFormat始终都要创建的
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date =new Date();
String oldDate = sdf.format(date);
System.out.println(oldDate);
如果:
2018-07-30 21:37:27
2.将字符串转化成指定格式的时间
//2.将字符串转化成指定格式的时间
//SimpleDateFormat始终都要创建的
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
try {
Date date2= sdf2.parse("2018-11-11 11_22_33");
System.out.println(date2);
} catch (ParseException e) {
e.printStackTrace();
}
结果:
Sun Nov 11 11:22:33 CST 2018
3.关于秒级的计算,用gettime
Date()
Date(int year, int month, int date)
Date(int year, int month, int date, int hrs, int min)
Date(int year, int month, int date, int hrs, int min, int sec)
Date(String s)[过时]
getTime()
返回的是long
//getTime
Date d1=new Date();
Date d2=new Date(d1.getTime()+3000);
System.out.println(d1);
System.out.println(d2);//延迟3秒