Java基礎(chǔ)篇之如何使用日期與時(shí)間API技術(shù)

這篇文章主要介紹“Java基礎(chǔ)篇之如何使用日期與時(shí)間API技術(shù)”,在日常操作中,相信很多人在Java基礎(chǔ)篇之如何使用日期與時(shí)間API技術(shù)問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對(duì)大家解答”Java基礎(chǔ)篇之如何使用日期與時(shí)間API技術(shù)”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比甘谷網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式甘谷網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋甘谷地區(qū)。費(fèi)用合理售后完善,10年實(shí)體公司更值得信賴。

一、時(shí)間和日期

在系統(tǒng)開發(fā)中,日期與時(shí)間作為重要的業(yè)務(wù)因素,起到十分關(guān)鍵的作用,例如同一個(gè)時(shí)間節(jié)點(diǎn)下的數(shù)據(jù)生成,基于時(shí)間范圍的各種數(shù)據(jù)統(tǒng)計(jì)和分析,集群節(jié)點(diǎn)統(tǒng)一時(shí)間避免超時(shí)等。

在時(shí)間和日期中有幾個(gè)關(guān)鍵概念:

  • 日期:通常年月日的組合表示當(dāng)前日期。

  • 時(shí)間:通常時(shí)分秒的組合表示當(dāng)前時(shí)間。

  • 時(shí)區(qū):世界各國家與地區(qū)經(jīng)度不同,劃分24個(gè)標(biāo)準(zhǔn)時(shí)區(qū),相鄰時(shí)區(qū)的時(shí)間相差一個(gè)小時(shí)。

  • 時(shí)間戳:從UTC時(shí)間的1970-1-1 00:00:00起到現(xiàn)在的總秒數(shù)。

日期和時(shí)間的用法在系統(tǒng)中通常是獲取時(shí)間和一些常見的計(jì)算與格式轉(zhuǎn)換處理,在一些垮時(shí)區(qū)的業(yè)務(wù)中就會(huì)變的復(fù)雜很多,例如在電商業(yè)務(wù)中的全球貿(mào)易或者海淘等。

二、JDK原生API

1、Date基礎(chǔ)

基礎(chǔ)用法

java.sql.Date繼承java.util.Date,相關(guān)方法也大部分直接調(diào)用父類方法。

public class DateTime01 {
    public static void main(String[] args) {
        long nowTime = System.currentTimeMillis() ;
        java.util.Date data01 = new java.util.Date(nowTime);
        java.sql.Date date02 = new java.sql.Date(nowTime);
        System.out.println(data01);
        System.out.println(date02.getTime());
    }
}
打?。?
Fri Jan 29 15:11:25 CST 2021
1611904285848

計(jì)算規(guī)則

public class DateTime02 {
    public static void main(String[] args) {
        Date nowDate = new Date();
        System.out.println("年:"+nowDate.getYear());
        System.out.println("月:"+nowDate.getMonth());
        System.out.println("日:"+nowDate.getDay());
    }
}

年份:當(dāng)前時(shí)間減去1900;

public int getYear() {
    return normalize().getYear() - 1900;
}

月份:0-11表示1-12月份;

public int getMonth() {
    return normalize().getMonth() - 1;
}

天份:正常表示;

public int getDay() {
    return normalize().getDayOfWeek() - BaseCalendar.SUNDAY;
}

格式轉(zhuǎn)換

非線程安全的日期轉(zhuǎn)換API,該用法在規(guī)范的開發(fā)中是不允許使用的。

public class DateTime02 {
    public static void main(String[] args) throws Exception {
        // 默認(rèn)轉(zhuǎn)換
        DateFormat dateFormat01 = new SimpleDateFormat() ;
        String nowDate01 = dateFormat01.format(new Date()) ;
        System.out.println("nowDate01="+nowDate01);
        // 指定格式轉(zhuǎn)換
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat dateFormat02 = new SimpleDateFormat(format);
        String nowDate02 = dateFormat02.format(new Date()) ;
        System.out.println("nowDate02="+nowDate02);
        // 解析時(shí)間
        String parse = "yyyy-MM-dd HH:mm";
        SimpleDateFormat dateFormat03 = new SimpleDateFormat(parse);
        Date parseDate = dateFormat03.parse("2021-01-18 16:59:59") ;
        System.out.println("parseDate="+parseDate);
    }
}

作為JDK初始版本就使用的日期和時(shí)間,Date類一直在項(xiàng)目中使用,但是相關(guān)API的方法都已經(jīng)基本廢棄,通常使用一些二次封裝的時(shí)間組件。該API的設(shè)計(jì)堪稱Java中的最爛。

2、Calendar升級(jí)

Calendar作為一個(gè)抽象類,定義日期時(shí)間相關(guān)轉(zhuǎn)換與計(jì)算的方法,這個(gè)類目測(cè)

public class DateTime04 {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR,2021);
        calendar.set(Calendar.MONTH,1);
        calendar.set(Calendar.DAY_OF_MONTH,12);
        calendar.set(Calendar.HOUR_OF_DAY,23);
        calendar.set(Calendar.MINUTE,59);
        calendar.set(Calendar.SECOND,59);
        calendar.set(Calendar.MILLISECOND,0);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
        Date defDate = calendar.getTime();
        System.out.println(defDate+"||"+dateFormat.format(defDate));
    }
}
輸出:Fri Feb 12 23:59:59 CST 2021||2021-02-12 23:59:59

直觀感覺,Date中相關(guān)方法遷移Calendar實(shí)現(xiàn),簡化Date的功能側(cè)重對(duì)日期與時(shí)間的實(shí)體封裝,Calendar復(fù)雜相關(guān)計(jì)算策略,DateFormat依舊用來做格式處理。但是Calendar依舊很少被使用,上述基礎(chǔ)API就已經(jīng)是很好的說明了。

3、JDK1.8升級(jí)API

Java8之后的版本中,核心API類包括LocalDate-日期、LocalTime-時(shí)間、LocalDateTime-日期加時(shí)間。

  • LocalDate:日期描述是final修飾的不可變類,默認(rèn)格式y(tǒng)yyy-MM-dd。

  • LocalTime:時(shí)間描述是final修飾的不可變類,默認(rèn)格式hh:mm:ss.zzz。

  • LocalDateTime:日期與時(shí)間描述final修飾的不可變類。

public class DateTime05 {
    public static void main(String[] args) {
        // 日期:年-月-日
        System.out.println(LocalDate.now());
        // 時(shí)間:時(shí)-分-秒-毫秒
        System.out.println(LocalTime.now());
        // 日期時(shí)間:年-月-日 時(shí)-分-秒-毫秒
        System.out.println(LocalDateTime.now());
        // 日期節(jié)點(diǎn)獲取
        LocalDate localDate = LocalDate.now();
        System.out.println("[" + localDate.getYear() +
                "年];[" + localDate.getMonthValue() +
                "月];[" + localDate.getDayOfMonth()+"日]");
        // 計(jì)算方法
        System.out.println("1年后:" + localDate.plusYears(1));
        System.out.println("2月前:" + localDate.minusMonths(2));
        System.out.println("3周后:" + localDate.plusWeeks(3));
        System.out.println("3天前:" + localDate.minusDays(3));

        // 時(shí)間比較
        LocalTime localTime1 = LocalTime.of(12, 45, 45); ;
        LocalTime localTime2 = LocalTime.of(16, 30, 30); ;
        System.out.println(localTime1.isAfter(localTime2));
        System.out.println(localTime2.isAfter(localTime1));
        System.out.println(localTime2.equals(localTime1));

        // 日期和時(shí)間格式
        LocalDateTime localDateTime = LocalDateTime.now() ;
        LocalDate myLocalDate = localDateTime.toLocalDate();
        LocalTime myLocalTime = localDateTime.toLocalTime();
        System.out.println("日期:" + myLocalDate);
        System.out.println("時(shí)間:" + myLocalTime);
    }
}

如果作為JodaTime組件的深度用戶,對(duì)這個(gè)幾個(gè)API使用基本無壓力。

4、時(shí)間戳

時(shí)間戳也是業(yè)務(wù)中常用的方式,基于Long類型表示時(shí)間,在很多時(shí)候遠(yuǎn)比常規(guī)日期與時(shí)間的格式更好用。

public class DateTime06 {
    public static void main(String[] args) {
        // 精確到毫秒級(jí)別
        System.out.println(System.currentTimeMillis());
        System.out.println(new Date().getTime());
        System.out.println(Calendar.getInstance().getTime().getTime());
        System.out.println(LocalDateTime.now().toInstant(
                ZoneOffset.of("+8")).toEpochMilli());
    }
}

這里需要注意的是在實(shí)際業(yè)務(wù)中由于獲取時(shí)間戳的方式是多樣的,所以建議統(tǒng)一工具方法,和規(guī)定精確度,避免部分精確到秒部分精確到毫秒的問題,這樣可以規(guī)避在使用時(shí)相互轉(zhuǎn)換的情況。

三、JodaTime組件

在Java8之前JodaTime組件是大部分系統(tǒng)中的常見選擇,有很多方便好用的日期與時(shí)間的處理方法封裝。

基礎(chǔ)依賴:

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
</dependency>

在joda-time提供的組件之上做一個(gè)簡單的工具類封裝,保證業(yè)務(wù)處理風(fēng)格統(tǒng)一。

public class JodaTimeUtil {

    // 時(shí)間格式
    public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    private JodaTimeUtil (){}

    // 獲取當(dāng)前時(shí)間
    public static DateTime getCurrentTime (){
        return new DateTime() ;
    }

    // 獲取指定時(shí)間
    public static DateTime getDateTime (Object obj){
        return new DateTime(obj) ;
    }

    // 把時(shí)間以指定格式轉(zhuǎn)換為字符串
    public static String getNowDate (Date date, String format){
        return new DateTime(date).toString(format) ;
    }

    // 獲取星期時(shí)間
    public static String getWeek (Object date){
        DateTime time = getDateTime (date) ;
        String week = null ;
        switch (time.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                week = "星期日";
                break;
            case DateTimeConstants.MONDAY:
                week = "星期一";
                break;
            case DateTimeConstants.TUESDAY:
                week = "星期二";
                break;
            case DateTimeConstants.WEDNESDAY:
                week = "星期三";
                break;
            case DateTimeConstants.THURSDAY:
                week = "星期四";
                break;
            case DateTimeConstants.FRIDAY:
                week = "星期五";
                break;
            case DateTimeConstants.SATURDAY:
                week = "星期六";
                break;
            default:
                break;
        }
        return week ;
    }
}

四、源代碼地址

GitHub·地址
https://github.com/cicadasmile/java-base-parent
GitEE·地址
https://gitee.com/cicadasmile/java-base-parent

到此,關(guān)于“Java基礎(chǔ)篇之如何使用日期與時(shí)間API技術(shù)”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

當(dāng)前名稱:Java基礎(chǔ)篇之如何使用日期與時(shí)間API技術(shù)
分享鏈接:http://bm7419.com/article40/igsiho.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供移動(dòng)網(wǎng)站建設(shè)、App開發(fā)網(wǎng)站設(shè)計(jì)公司、電子商務(wù)品牌網(wǎng)站制作、外貿(mào)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)