zoukankan      html  css  js  c++  java
  • 廖雪峰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)));
        }
    
  • 相关阅读:
    LVS负载均衡软件使用及(LVS简介、三种工作模式、十种调度算法)
    Nginx+Tomcat实现负载均衡!
    Nginx实现HTTP及TCP负载均衡
    Nginx 反向代理报400错误解决方法!
    Session服务器之Session复制!
    反射、内置方法和元类
    多态和绑定方法
    封装和继承
    面向对象编程
    软件目录规范下的AMT+购物车(简易版)的实现
  • 原文地址:https://www.cnblogs.com/csj2018/p/10698924.html
Copyright © 2011-2022 走看看