java sql 日期_廖雪峰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对象和数据库类型做正确的映射。

ce1df5ae68f8975fcdc7aee75b8764c0.png

新旧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)));

}

e235d5f230ba850daa4c13f6a35f437b.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值