Java8日期时间

版权声明:杨福东 https://blog.csdn.net/qq_31120741/article/details/83341017

Java8日期时间


java8提供了三个处理日期时间的工具类,LocalDate操作年月日,LocalTime操作时分秒,LocalDateTime操作日期加时间,可以由LocalDate和LocalTime构造LocalDateTime。三个类的方法相似,有对日期或时间的加减,格式化,获取等。以LocalDate为例,简单介绍常用的方法。

LocalDate

LocalDate()指定年月日构造LocalDate对象

private LocalDate(int year, int month, int dayOfMonth) {
        this.year = year;
        this.month = (short) month;
        this.day = (short) dayOfMonth;
    }

now(),有三个重载,分别时默认当前时区当前日期,指定时区的当前日期,指定时间间隔的时钟

public static LocalDate now() {
        return now(Clock.systemDefaultZone());
    }
public static LocalDate now(ZoneId zone) {
        return now(Clock.system(zone));
    }
public static LocalDate now(Clock clock) {
        Objects.requireNonNull(clock, "clock");
        // inline to avoid creating object and Instant checks
        final Instant now = clock.instant();  // called once
        ZoneOffset offset = clock.getZone().getRules().getOffset(now);
        long epochSec = now.getEpochSecond() + offset.getTotalSeconds();  // overflow caught later
        long epochDay = Math.floorDiv(epochSec, SECONDS_PER_DAY);
        return LocalDate.ofEpochDay(epochDay);
    }

parse(),两个重载,解析字符转为LocalDate

public static LocalDate parse(CharSequence text) {
        return parse(text, DateTimeFormatter.ISO_LOCAL_DATE);
    }
public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) {
        Objects.requireNonNull(formatter, "formatter");
        return formatter.parse(text, LocalDate::from);
    }

get(),有多种get(),可以获取日期字段

public int getYear() {
        return year;
    }
public Month getMonth() {
        return Month.of(month);
    }

plus(),有多种plus(),按指定值加上当前日期

public LocalDate plusDays(long daysToAdd) {
        if (daysToAdd == 0) {
            return this;
        }
        long mjDay = Math.addExact(toEpochDay(), daysToAdd);
        return LocalDate.ofEpochDay(mjDay);
    }

minus(),有多种minus(),按当前日期减去的指定值

public LocalDate minusYears(long yearsToSubtract) {
        return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
    }

format(),按指定规则格式化转换日期

 public String format(DateTimeFormatter formatter) {
        Objects.requireNonNull(formatter, "formatter");
        return formatter.format(this);
    }

猜你喜欢

转载自blog.csdn.net/qq_31120741/article/details/83341017
今日推荐