目录
LocalDate、LocalTime、LocalDateTime
日期
注意:阿里规范说能用新的时间类就用新的
jdk8之前:
Date
-
继承关系图(java.util.Date java.sql.Date java.sql.Time java.sql.Timestamp 关系)
-
常见API
Date() :取得当前时间
Date(long date):以给定的毫秒数 产生的Date
long getTime():拿到时间的毫秒数
boolean after(Date when)
boolean before(Date when)
int compareTo(Date anotherDate)
boolean equals(Object obj)
static Date from(Instant instant)
Calendar
对时间的一个操作的类
-
常见API
static Calendar getInstance()
int get(int field)
Date getTime() :calendar转换为java.util.Date
void set(int field, int value)
void setTime(Date date):将Date转换为calendar
Instant toInstant()
SimpleDateFormat
用于格式化时间
线程不安全
为什么SimpleDateFormat是线程不安全的?
我看过源代码,因为当其他线程在调用SimpleDateFormat时会将原来的时间clear清空掉,会将数据污染了 ,所以是不安全的
如何让它变得安全?在安全的环境下面去使用SimpleDateFormat就行了(在方法里面使用就是安全的)
//数字格式化
Format (NumberFormat DateFormat)
@Test
public void test6(){
DecimalFormat df = new DecimalFormat("##,###");
try {
Number number = df.parse("20.3");
String str = df.format(10000000);
System.out.println(number);
System.out.println(str);
} catch (ParseException e) {
e.printStackTrace();
}
}
//日期格式化
@Test
public void test5(){
Date d1 = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdf.format(d1);
System.out.println(str);
try {
Date d2 = sdf.parse("2020-09-09 10:09:25");
System.out.println(d2);
} catch (ParseException e) {
e.printStackTrace();
}
}
jdk8及以后的版本
(跟上面的用法差不多)
Instant
相当于Date,获取当前时间,注意默认是UTC时间,与我们的时间相差了八个小时,使用时需要在此基础上加上八个小时
使用静态方法 拿到对象 now();
/**获取当前时间,UTC时间*/
Instant instant = Instant.now();
System.out.println(instant);
/**转换成我们使用的东八区时间*/
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);
LocalDate、LocalTime、LocalDateTimeDuration
相当于calender类,对时间日期的操作的类
Duration
拿到时间
Period
拿到日期
DateTimeFormatter
使用静态方法 ofPattern()拿到对象
对时间日期进行格式化
//格式化时间的格式//格式化LocalDateTime
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("YYYY年MM月dd日 HH时mm分ss秒");
//用格式化时间的对象对LocalDateTime.now()时间进行格式化
String format = dtf.format(LocalDateTime.now());
System.out.println(format);
对时间日期进行格式化
//格式化时间//格式化Instant时间
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss") .withZone(ZoneId.systemDefault());
String format = dateTimeFormatter.format(Instant.now());
System.out.println(format);