廖雪峰Java7处理日期和时间-4最佳实践-最佳实践
jdk提供了2套新旧的API来处理日期和时间。
- java.util
* Date
* Calendar - java.time(JDK>=1.8)
* Localdate
* LocalTime
* LocalDateTime
* ZonedDateTime
* Instant
java.sql时间
java.util.Date表示日期和时间:
- getYear()/getMonth()/getDate()
- getHours()/getMinutes()/getSeconds()
java.sql.Date继承自java.util.Date,但去除了时分秒,仅表示日期:
getHours() /getMinutes() /getSeconds() {
throw new IllegalArgumentException();
}
类似java.sql.Time仅表示时间
getYear() /getMont() /getDate() {
throw new IllegalArgumentException();
}
java.sql.TimeStamp表示SQL数据库的TIMESTAMP
int nanos:将毫秒数清零,用int表示纳秒
之所以介绍这几个类,是因为将来在访问关系数据库的时候,需要把Java对象和数据库类型做正确的映射。
新旧API之间的转换
旧的API:java.util.Date, java.util.Calendar
新的API:Instant, ZonedDateTime, LocalDateTime
1.先
public static void main(String[] args) {
System.out.println(epoch2String(1480468500000L,Locale.CHINA,"Asia/Shanghai"));
System.out.println(epoch2String(1480468500000L,Locale.US,"America/New_York"));
//Locale对象是地区,如CHINA,US,UK,CANDA
//FormatStyle有FULL,MEDIUM,SHORT,LONG
DateTimeFormatter dtf1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
DateTimeFormatter dtf2 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
DateTimeFormatter dtf3 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
DateTimeFormatter dtf4 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
System.out.println(dtf1.format(ZonedDateTime.now()));
System.out.println(dtf2.format(ZonedDateTime.now()));
System.out.println(dtf3.format(ZonedDateTime.now()));
System.out.println(dtf4.format(ZonedDateTime.now()));
}
static String epoch2String(long epoch, Locale lo, String zoneId){
Instant ins = Instant.ofEpochMilli(epoch);
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM,FormatStyle.SHORT);
return f.withLocale(lo).format(ZonedDateTime.ofInstant(ins,ZoneId.of(zoneId)));
}
![](https://img2018.cnblogs.com/blog/1418970/201904/1418970-20190413095531755-2083364713.png)