java8 之LocalDate類

學習連接地址:https://www.tutorialspoint.com/java8/java8_datetime_api.htm


import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;

public class TimeDemoTest {
    public static void main(String[] args) {
        // test1();
        //Get the current date
        Date currentDate = new Date();
        System.out.println("Current date: " + currentDate);

        //Get the instant of current date in terms of milliseconds
        Instant now = currentDate.toInstant();
        System.out.println("now="+now);
        ZoneId currentZone = ZoneId.systemDefault();

        LocalDateTime localDateTime = LocalDateTime.ofInstant(now, currentZone);
        System.out.println("Local date: " + localDateTime);

        ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, currentZone);
        System.out.println("Zoned date: " + zonedDateTime);

    }
    public static void testAdjusters(){

        LocalDate today = LocalDate.now();
        System.out.println("today=" + today);

        LocalDate nextTuesday= today.with(TemporalAdjusters.next(DayOfWeek.TUESDAY));
        System.out.println("Next Tuesday on:"+nextTuesday);


        //本月的第一個星期四是幾號
        LocalDate firstInYear = LocalDate.of(today.getYear(),today.getMonth(),1);
        LocalDate secondSaturday = firstInYear.with(TemporalAdjusters.nextOrSame(DayOfWeek.THURSDAY));
        System.out.println("firstInYear="+firstInYear+",secondSaturday="+secondSaturday);


        LocalDate firstDayOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
        LocalDate firstDayOfNextMonth = today.with(TemporalAdjusters.firstDayOfNextMonth());
        LocalDate firstDayOfYear = today.with(TemporalAdjusters.firstDayOfYear());
        LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear());
        LocalDate firstDayOfNextYear = today.with(TemporalAdjusters.firstDayOfNextYear());
        System.out.println("firstDayOfMonth="+firstDayOfMonth);
        System.out.println("lastDayOfMonth="+lastDayOfMonth);
        System.out.println("firstDayOfNextMonth="+firstDayOfNextMonth);
        System.out.println("firstDayOfYear="+firstDayOfYear);
        System.out.println("lastDayOfYear="+lastDayOfYear);
        System.out.println("firstDayOfNextYear="+firstDayOfNextYear);
    }
    public static void testDuration() {
        LocalTime time1 = LocalTime.now();
        Duration twoHours = Duration.ofHours(2);
        LocalTime time2 = time1.plus(twoHours);
        Duration duration = Duration.between(time1, time2);
        System.out.println("duration=" + duration);
        System.out.println(duration.getSeconds() + "," + duration.getUnits());

    }

    public static void testPeriod() {
        LocalDate today = LocalDate.now();
        System.out.println("today=" + today);
        // 1月後日期
        LocalDate nextMonth = today.plus(1, ChronoUnit.MONTHS);
        System.out.println("nextMonth=" + nextMonth);

        Period period = Period.between(nextMonth, today);
        System.out.println(period);
        System.out.println(period.getMonths() + "," + period.getDays() + "," + period.getUnits());

    }

    public static void testChromoUnits() {
        LocalDate today = LocalDate.now();
        System.out.println("today=" + today);

        // 一個星期後
        LocalDate nextweek = today.plus(1, ChronoUnit.WEEKS);
        // LocalDate nextweek = today.plus(7,ChronoUnit.DAYS);
        System.out.println("nextweek=" + nextweek);

        // 1月後日期
        LocalDate nextMonth = today.plus(1, ChronoUnit.MONTHS);
        System.out.println("nextMonth=" + nextMonth);

        // 一年後日期
        LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
        System.out.println("nextYear=" + nextYear);

        // 10年後日期
        LocalDate nextTenyear = today.plus(1, ChronoUnit.DECADES);
        System.out.println("Date after ten year:" + nextTenyear);
    }

    public static void testZonedDateTime() {
        ZonedDateTime date1 = ZonedDateTime.parse("2007-12-03T10:15:30+05:30[Asia/Karachi]");
        System.out.println("date1=" + date1);
        ZoneId id = ZoneId.of("Europe/Paris");
        System.out.println("ZondId:" + id);
        ZoneId currentZone = ZoneId.systemDefault();
        System.out.println("currentZone=" + currentZone);
    }

    public static void testLocalDateTime() {
        LocalDateTime currentTime = LocalDateTime.now();
        LocalDate todaydate = currentTime.toLocalDate();
        Month todaymonth = currentTime.getMonth();
        int todayday = currentTime.getDayOfMonth();
        int todayseconds = currentTime.getSecond();
        System.out.println("now=" + currentTime);
        System.out.println("todaydate=" + todaydate);
        System.out.println("Month=" + todayday + ",day=" + todayday + ",todayseconds=" + todayseconds);
        // 設置月的第10天,年爲2015
        LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2015);
        System.out.println("date2=" + date2);

        // 年月日
        LocalDate date3 = LocalDate.of(2015, 10, 12);
        System.out.println("date3=" + date3);

        // 設置時、分
        LocalTime date4 = LocalTime.of(22, 15);
        System.out.println("date4=" + date4);

        // string轉成LocalTime類型
        LocalTime date5 = LocalTime.parse("22:15:16");
        System.out.println("date5=" + date5);
    }

    public static void selfFormat() {
        YearMonth currentYearMonth = YearMonth.now();
        System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
        YearMonth creditCardExpiry = YearMonth.of(2018, Month.FEBRUARY);
        System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
        LocalDate today = LocalDate.now();
        if (today.isLeapYear()) {
            // 閏年
            System.out.println("This year is Leap year");
        } else {
            // 平年
            System.out.println("2014 is not a Leap year");
        }
        LocalDate oneday = today.minus(10, ChronoUnit.DAYS);
        System.out.println("today=" + today + ",oneday=" + oneday);
        // 兩個日期之間包含多少天,多少個月
        Period period = Period.between(oneday, today);
        System.out.println("相差多少天:" + period.getDays() + "相差幾個月=" + period.getMonths() + "相差幾年=" + period.getYears());
        Instant timestamp = Instant.now();
        System.out.println("當前時間戳=" + timestamp);
        // 格式化日期

        String dayAfterTommrrow = "20150118";
        LocalDate formatted = LocalDate.parse(dayAfterTommrrow, DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println("day=" + formatted);
        System.out.printf("Date generated from String %s is %s %n", dayAfterTommrrow, formatted);
        // 使用自定義的格式器來解析日期
        String goodFriday = "04 18 2014";
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM dd yyyy");
            LocalDate holiday = LocalDate.parse(goodFriday, formatter);
            System.out.printf("Successfully parsed String %s, date is %s%n", goodFriday, holiday);
        } catch (DateTimeParseException ex) {
            System.out.printf("%s is not parsable!%n", goodFriday);
            ex.printStackTrace();
        }
        // 在Java 8中對日期進行格式化,轉換成字符串
        LocalDateTime arrivalDate = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM dd yyyy hh:mm a");
        String landing = arrivalDate.format(formatter);
        System.out.printf("Arriving at : %s %n", landing);

    }

    public static void afterAndBefore() {
        LocalDate today = LocalDate.now();
        LocalDate onedate = LocalDate.of(2014, 1, 15);
        if (onedate.isAfter(today)) {
            System.out.println("onedate comes after today");
        } else {
            System.out.println("onedate is long long ago");
        }
        LocalDate beforeday = today.minus(3, ChronoUnit.DAYS);
        System.out.println(beforeday);
        if (beforeday.isBefore(today)) {
            System.out.println("beforeday is day before today");
        }
    }

    public static void getClock() {
        // Returns the current time based on your system clock and set to UTC.
        Clock clock = Clock.systemUTC();
        System.out.println("Clock : " + clock);
        // Returns time based on system clock zone Clock defaultClock =
        Clock.systemDefaultZone();
        System.out.println("Clock : " + clock);
    }

    public static void getTime() {
        LocalTime time = LocalTime.now();
        // 當前時間是不包含日期的,因爲LocalTime只有時間,沒有日期。
        System.out.println("now=" + time);
        LocalTime newtime = time.plusHours(2);// 現在時間加上2
        System.out.println("Time after 2 hours : " + newtime);

    }

    public static void equal() {
        LocalDate startdate = LocalDate.of(2016, 7, 15);
        LocalDate enddate = LocalDate.of(2016, 10, 10);
        if (startdate.equals(enddate)) {
            System.out.printf("Today %s and date1 %s are same date %n", startdate, enddate);
        } else {
            System.out.printf("Today %s and date1 %s are not same date %n", startdate, enddate);
        }
    }

    public static void test1() {
        // 輸出當前的日期2016-12-16
        LocalDate today = LocalDate.now();
        System.out.println("Today's Local date:" + today);
        LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
        // 獲取1周後的日期
        System.out.println("Date after 1 week : " + nextWeek);
        LocalDate beforeWeek = today.minus(1, ChronoUnit.WEEKS);
        // 獲取1周後的日期
        System.out.println("Date before 1 week : " + beforeWeek);

        LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
        System.out.println("Date before 1 year : " + previousYear);
        LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
        System.out.println("Date after 1 year : " + nextYear);

    }

    public static void now() {
        LocalDate today = LocalDate.now();
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();
        // 輸入當前日期的年月日
        System.out.printf("Year:%d Month:%d day:%d\t %n", year, month, day);
    }

    public static void setDate() {
        LocalDate dateofBirth = LocalDate.of(2010, 10, 10);
        // 在Java 8中如何獲取某個特定的日期
        System.out.println("我的生日的那天是:" + dateofBirth);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章