Java8中的LocalDateTime工具類__Java

來源:互聯網
上載者:User

網上搜尋了半天都沒有找到Java8的LocalDateTime的工具類,只好自己寫了一個,常用功能基本都有。還在用Date的Java同道該換換了。

個人項目地址:https://github.com/KingBoyWorld/common.git,Common模組中有很多實用的工具包,都是最佳化過的。

工具類

package com.kingboy.common.utils.date;import java.time.*;import java.time.format.DateTimeFormatter;import java.time.temporal.ChronoUnit;import java.time.temporal.TemporalUnit;import java.util.Date;/* * @author kingboy * @Date 2017/7/22 下午2:12 * @Description LocalDateTimeUtils is used to Java8中的時間類 */public class LocalDateTimeUtils {    //擷取目前時間的LocalDateTime對象    //LocalDateTime.now();    //根據年月日構建LocalDateTime    //LocalDateTime.of();    //比較日期先後    //LocalDateTime.now().isBefore(),    //LocalDateTime.now().isAfter(),    //Date轉換為LocalDateTime    public static LocalDateTime convertDateToLDT(Date date) {        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());    }    //LocalDateTime轉換為Date    public static Date convertLDTToDate(LocalDateTime time) {        return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());    }    //擷取指定日期的毫秒    public static Long getMilliByTime(LocalDateTime time) {        return time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();    }    //擷取指定日期的秒    public static Long getSecondsByTime(LocalDateTime time) {        return time.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();    }    //擷取指定時間的指定格式    public static String formatTime(LocalDateTime time,String pattern) {        return time.format(DateTimeFormatter.ofPattern(pattern));    }    //擷取目前時間的指定格式    public static String formatNow(String pattern) {        return  formatTime(LocalDateTime.now(), pattern);    }    //日期加上一個數,根據field不同加不同值,field為ChronoUnit.*    public static LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {        return time.plus(number, field);    }    //日期減去一個數,根據field不同減不同值,field參數為ChronoUnit.*    public static LocalDateTime minu(LocalDateTime time, long number, TemporalUnit field){        return time.minus(number,field);    }    /**     * 擷取兩個日期的差  field參數為ChronoUnit.*     * @param startTime     * @param endTime     * @param field  單位(年月日時分秒)     * @return     */    public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {        Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));        if (field == ChronoUnit.YEARS) return period.getYears();        if (field == ChronoUnit.MONTHS) return period.getYears() * 12 + period.getMonths();        return field.between(startTime, endTime);    }    //擷取一天的開始時間,2017,7,22 00:00    public static LocalDateTime getDayStart(LocalDateTime time) {        return time.withHour(0)                .withMinute(0)                .withSecond(0)                .withNano(0);    }    //擷取一天的結束時間,2017,7,22 23:59:59.999999999    public static LocalDateTime getDayEnd(LocalDateTime time) {        return time.withHour(23)                .withMinute(59)                .withSecond(59)                .withNano(999999999);    }}

測試類別

package com.kingboy.common.localdatetimeutils;import com.kingboy.common.utils.date.LocalDateTimeUtils;import org.junit.Test;import java.time.LocalDateTime;import java.time.temporal.ChronoUnit;import static com.kingboy.common.utils.date.LocalDateTimeUtils.getDayEnd;import static com.kingboy.common.utils.date.LocalDateTimeUtils.getDayStart;/** * @author kingboy * @Date 2017/7/22 下午7:16 * @Description LocaDateTimeUtilsTest is used to 測試LocalDateTime工具 */public class LocaDateTimeUtilsTest {    @Test    public void format_test() {        System.out.println(LocalDateTimeUtils.formatNow("yyyy年MM月dd日 HH:mm:ss"));    }    @Test    public void betweenTwoTime_test() {        LocalDateTime start = LocalDateTime.of(1993, 10, 13, 11, 11);        LocalDateTime end = LocalDateTime.of(1994, 11, 13, 13, 13);        System.out.println("年:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.YEARS));        System.out.println("月:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.MONTHS));        System.out.println("日:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.DAYS));        System.out.println("半日:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.HALF_DAYS));        System.out.println("小時:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.HOURS));        System.out.println("分鐘:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.MINUTES));        System.out.println("秒:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.SECONDS));        System.out.println("毫秒:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.MILLIS));        //=============================================================================================        /*                                      年:1                                      月:13                                      日:396                                      半日:792                                      小時:9506                                      分鐘:570362                                      秒:34221720                                      毫秒:34221720000        */    }    @Test    public void plus_test() {        //增加二十分鐘        System.out.println(LocalDateTimeUtils.formatTime(LocalDateTimeUtils.plus(LocalDateTime.now(),                20,                ChronoUnit.MINUTES), "yyyy年MM月dd日 HH:mm"));        //增加兩年        System.out.println(LocalDateTimeUtils.formatTime(LocalDateTimeUtils.plus(LocalDateTime.now(),                2,                ChronoUnit.YEARS), "yyyy年MM月dd日 HH:mm"));        //=============================================================================================        /*                                        2017年07月22日 22:53                                        2019年07月22日 22:33         */    }    @Test    public void dayStart_test() {        System.out.println(getDayStart(LocalDateTime.now()));        System.out.println(getDayEnd(LocalDateTime.now()));        //=============================================================================================        /*                                        2017-07-22T00:00                                2017-07-22T23:59:59.999999999         */    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.