• 廖雪峰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)));
        }
    
  • 相关阅读:
    容斥原理算法总结(bzoj 2986 2839)
    网络流系列算法总结(bzoj 3438 1061)
    bzoj 2746: [HEOI2012]旅行问题 AC自动机fail树
    bzoj 3283: 运算器 扩展Baby Step Giant Step && 快速阶乘
    计算几何考场绘图技巧
    bzoj 1845: [Cqoi2005] 三角形面积并 扫描线
    bzoj 3784: 树上的路径 堆维护第k大
    BZOJ 1231: [Usaco2008 Nov]mixup2 混乱的奶牛
    BZOJ 1112: [POI2008]砖块Klo
    BZOJ 1003: [ZJOI2006]物流运输trans DP+最短路
  • 原文地址:https://www.cnblogs.com/csj2018/p/10698924.html
Copyright © 2020-2023  润新知