java - LocalDate与LocalTime用法

文章转载自https://blog.csdn.net/u010031939/article/details/53908467,感谢作者的分享
文章主要列举了一下几个类的使用方法

LocalDate,只包含日期
LocalTime,只包含时间
LocalDateTime,包含日期和时间
DateTimeFormatter,格式化日期/时间
TemporalAdjusters

ChronoUnit


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) {
        //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 calTotalDays() {
	//计算两个日期相差总天数
        LocalDate last = LocalDate.of(2018, 5, 1);
        LocalDate today = LocalDate.now();
        System.out.println(today.toEpochDay() - last.toEpochDay());
    }

    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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值