java8日期操作

public class DateTimeApiTest {
    public static void main(String[] args) throws InterruptedException {

    }



    private static void temporalAdjuster_AdjustInto() {
        LocalDateTime localDateTime = LocalDateTime.now();

        // 下个月的第一天
        // 以下方法效果一样
        // localDateTime.with(TemporalAdjusters.firstDayOfNextMonth());
        Temporal firstDayOfNextMonth = TemporalAdjusters.firstDayOfNextMonth().adjustInto(localDateTime);

        // 这个月第二个MONDAY
        Temporal dayOfWeekInMonth = (LocalDateTime) TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.MONDAY)
                .adjustInto(localDateTime);

        // 这个月最后一个MONDAY
        Temporal temporal2 = TemporalAdjusters.lastInMonth(DayOfWeek.MONDAY).adjustInto(localDateTime);

        // 这个月第一个MONDAY
        Temporal temporal3 = TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY).adjustInto(localDateTime);

        // 下一个THURSDAY。如果localDateTime是THURSDAY则返回localDateTime。 如果不返回localDateTime可以使用next()
        Temporal temporal4 = TemporalAdjusters.nextOrSame(DayOfWeek.THURSDAY).adjustInto(localDateTime);

        // 上一个THURSDAY。如果localDateTime是THURSDAY则返回localDateTime。 如果不返回localDateTime可以使用previous()
        Temporal temporal5 = TemporalAdjusters.previousOrSame(DayOfWeek.THURSDAY).adjustInto(localDateTime);

        // 自定义调整年月日
        Temporal temporal1 = TemporalAdjusters.ofDateAdjuster((LocalDate localDate1) -> {
            return LocalDate.of(2021, 12, 12);
        }).adjustInto(localDateTime);

    }

    private static void temporalAmount_Between() {
        // TemporalAmount两个实现类
        TemporalAmount period = Period.ZERO;
        TemporalAmount duration = Duration.ZERO;

        // Period是基于日期的实现,存储年、月和日
        LocalDate localDate = LocalDate.now();
        LocalDate firstDayOfNextMonth = localDate.with(TemporalAdjusters.firstDayOfNextMonth());
        Period periodBetween = Period.between(localDate, firstDayOfNextMonth);
        // 相差的年份
        int years = periodBetween.getYears();
        // 相差的月份
        int months = periodBetween.getMonths();
        // 相差的天数
        int days = periodBetween.getDays();

        // Duration是基于时间的实现,存储秒和纳秒
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime withOneHour = localDateTime.plusHours(1);
        Duration durationBetween = Duration.between(withOneHour,localDateTime);
        // 相差的秒
        long l = durationBetween.get(ChronoUnit.SECONDS);
        long l1 = durationBetween.abs().get(ChronoUnit.SECONDS);


        ///利用ChronoUnit来获取日期时间差///

        // 相差的天数
        long daysBetween = ChronoUnit.DAYS.between(localDateTime, withOneHour);
        // 相差的小时
        long hoursBetween = ChronoUnit.HOURS.between(localDateTime, withOneHour);
        // 相差的秒数
        long secondsBetween = ChronoUnit.SECONDS.between(localDateTime, withOneHour);
    }

    private static void temporalField() {
        // TemporalField和它的实现类
        TemporalField temporalField = ChronoField.DAY_OF_WEEK;
        TemporalField temporalField1 = IsoFields.DAY_OF_QUARTER;
        TemporalField temporalField2 = JulianFields.JULIAN_DAY;

        // ChronoField常用方法
        ChronoField dayOfMonth = ChronoField.DAY_OF_MONTH;
        // 获取DAY_OF_MONTH的取值区间
        ValueRange range = dayOfMonth.range();
        long maximum = range.getMaximum();
        long minimum = range.getMinimum();
        long smallestMaximum = range.getSmallestMaximum();
        long largestMinimum = range.getLargestMinimum();

        // 获取展示名
        String displayName = dayOfMonth.getDisplayName(Locale.CHINESE);
        System.out.println(displayName);
    }

    private static void temporalQuery() {
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDate localDate = TemporalQueries.localDate().queryFrom(localDateTime);

        LocalTime localTime = TemporalQueries.localTime().queryFrom(localDateTime);

        Chronology chronology = TemporalQueries.chronology().queryFrom(localDateTime);

        ZoneId zoneId = TemporalQueries.zone().queryFrom(localDateTime);

        TemporalUnit temporalUnit = TemporalQueries.precision().queryFrom(localDateTime);

        // 这种方式能达到同样的效果。通常使用这种方法
        LocalDate query = localDateTime.query(TemporalQueries.localDate());
    }

    private static void valueRange() {
        ValueRange of = ValueRange.of(1, 28, 31);
        // 最小值
        long minimum = of.getMinimum();
        // 最小值里的最小的
        long largestMinimum = of.getLargestMinimum();
        // 最大值里的最小的
        long smallestMaximum = of.getSmallestMaximum();
        // 最大值
        long maximum = of.getMaximum();
        // 取值是否是固定的。 因为最大值不固定,返回false
        boolean fixed = of.isFixed();

        ValueRange of1 = ValueRange.of(1, 31);
        // 返回ture。 因为最小值和最大值是固定的
        boolean fixed1 = of1.isFixed();
    }

    private static void chronoField() {
        OffsetDateTime offsetDateTime = OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.of("+08:00"));

        int i = offsetDateTime.get(ChronoField.AMPM_OF_DAY);
        int i1 = offsetDateTime.get(ChronoField.DAY_OF_WEEK);
        int i2 = offsetDateTime.get(ChronoField.DAY_OF_YEAR);
        int i3 = offsetDateTime.get(ChronoField.HOUR_OF_AMPM);
        int i4 = offsetDateTime.get(ChronoField.MINUTE_OF_DAY);
        int i5 = offsetDateTime.get(ChronoField.MINUTE_OF_HOUR);
        int i6 = offsetDateTime.get(ChronoField.YEAR_OF_ERA);
        int i7 = offsetDateTime.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR);
    }

    private static void dateTimeFormatter() {
        LocalDateTime localDateTime = LocalDateTime.now();
        String isoDateTime = DateTimeFormatter.ISO_DATE_TIME.format(localDateTime);
        String isoDate = DateTimeFormatter.ISO_DATE.format(localDateTime);
        String isoLocalDateTime = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(localDateTime);
        String isoWeekDate = DateTimeFormatter.ISO_WEEK_DATE.format(localDateTime);

//        String allFull = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).format(localDateTime);
        String allLong = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).format(localDateTime);
        String allMedium = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).format(localDateTime);
        String allShort = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).format(localDateTime);

        String dateLongTimeMedium = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.MEDIUM)
                .format(localDateTime);
        String dateLongTimeShort = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.SHORT)
                .format(localDateTime);

        String dateMediumTimeLong = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.LONG)
                .format(localDateTime);
        String dateMediumTimeShort = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT)
                .format(localDateTime);

        String dateShortTimeLong = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.LONG)
                .format(localDateTime);
        String dateShortTimeMedium = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.MEDIUM)
                .format(localDateTime);


        String yyyyMMddHHmmss = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                .format(localDateTime);
        String yyyyMMddEHHmmss = DateTimeFormatter.ofPattern("yyyy-MM-dd E HH:mm:ss")
                .format(localDateTime);
        String yyyyMMddAmOrPmHHmmss = DateTimeFormatter.ofPattern("yyyy-MM-dd a HH:mm:ss ")
                .format(localDateTime);
        String yyyyMMddAmOrPmhhmmss = DateTimeFormatter.ofPattern("yyyy-MM-dd a hh:mm:ss ")
                .format(localDateTime);
    }

    private static void dateTimeFormatterBuilder() {
        String localizedDateTimePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
                FormatStyle.LONG,
                FormatStyle.LONG,
                Chronology.of("ISO"),
                Locale.CHINA
        );

        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();

        String format = builder.optionalStart()
                .appendLiteral("当前时间:")
                .appendPattern("yyyy-MM-dd a hh:mm:ss")
                .optionalEnd()
                .toFormatter()
                .format(localDateTime);

        String format1 = new DateTimeFormatterBuilder().optionalStart()
                .appendLiteral("年:")
                .appendValue(ChronoField.YEAR)
                .appendLiteral("\r\n")
                .appendLiteral("月:")
                .appendValue(ChronoField.MONTH_OF_YEAR)
                .appendLiteral("\r\n")
                .appendLiteral("日:")
                .appendValue(ChronoField.DAY_OF_MONTH)
                .appendLiteral("\r\n")
                .appendLiteral("时间:")
                .appendPattern("a hh:mm:ss")
                .appendLiteral("\r\n")
                .optionalEnd()
                .toFormatter()
                .format(localDateTime);
    }

    private static void decimalStyle() {
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter iso = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
                .withChronology(Chronology.of("ISO"))
                .withDecimalStyle(DecimalStyle.ofDefaultLocale());

        String result = iso.format(localDateTime);
    }

    private static void Clock() throws InterruptedException {
        Clock defaultZoneClock = Clock.systemDefaultZone();
        long millis = defaultZoneClock.millis();
        Instant instant = defaultZoneClock.instant();

        Clock fromZoneId = Clock.system(ZoneId.of("Asia/Shanghai"));
        Instant instant1 = fromZoneId.instant();


        Clock offsetClock = Clock.offset(defaultZoneClock, Duration.ofHours(-2));
        Instant instant2 = offsetClock.instant();

        // 以固定频率来返回的Clock
        Clock tick = Clock.tick(defaultZoneClock, Duration.ofMillis(2));
        for (int i = 0; i < 5; i++) {
            System.out.println(tick.instant());
            Thread.sleep(2);
        }

        // Instant的值始终是同一个
        Clock fixed = Clock.fixed(Instant.now(), ZoneId.of("Asia/Shanghai"));
        Instant instant3 = fixed.instant();
    }

    private static void duration() {
        long oneHourSeconds = Duration.ofHours(1).getSeconds();
        long towHoursSeconds = Duration.of(2, ChronoUnit.HOURS).getSeconds();

        Duration zeroDuration = Duration.ZERO;
        Duration plus = zeroDuration.plus(10, ChronoUnit.SECONDS);
        long seconds = plus.getSeconds();

        Duration minus = zeroDuration.minus(10, ChronoUnit.SECONDS);
        long seconds1 = minus.getSeconds();
    }

    private static void instantLocalDateTimeDateConvert() {
        Instant instantNow = Instant.now(Clock.system(ZoneId.of("Asia/Shanghai")));
        long epochSecond = instantNow.getEpochSecond();

        // LocalDateTime、Instant之间转换
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instantNow, ZoneId.systemDefault());
        LocalDateTime localDateTime4 = Timestamp.from(instantNow).toLocalDateTime();

        Instant instant = localDateTime.toInstant(ZoneOffset.of("+08:00"));
        instant = localDateTime.atZone(ZoneId.of("Asia/Shanghai")).toInstant();
        long timeInSeconds = localDateTime.toEpochSecond(ZoneOffset.of("+08:00"));
        instant = Instant.ofEpochSecond(timeInSeconds);

        // localDateTime、Date之间的转换
        Instant instant1 = localDateTime.toInstant(ZoneOffset.of("+08:00"));
        Date from = Date.from(instant1);

        Date date = new Date();
        LocalDateTime localDateTime1 = LocalDateTime.ofInstant(date.toInstant(), ZoneId.of("Asia/Shanghai"));
        LocalDateTime localDateTime2 = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.of("Asia/Shanghai"));
        LocalDateTime localDateTime3 = Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
    }

    private static void yearMonthWeek() {
        Year now = Year.now();
        boolean leap = Year.isLeap(now.getValue());

        YearMonth yearMonth = YearMonth.now();
        int year = yearMonth.getYear();
        int monthValue = yearMonth.getMonthValue();

        MonthDay monthDay = MonthDay.now();
        int monthValue1 = monthDay.getMonthValue();
        int dayOfMonth = monthDay.getDayOfMonth();

        DayOfWeek wednesday = DayOfWeek.WEDNESDAY;
        int value = wednesday.getValue();
        DayOfWeek of = DayOfWeek.of(7);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hello_中年人

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值