Java8 java.time包下的日期类with()使用方法

with方法是将当前时间对象直接修改为参数指定的值,并且不改变当前时间对象,而是新生成了一个时间对象。

以LocalDateTime类为例,查看有以下with方法

LocalDateTime	with(TemporalAdjuster adjuster)

LocalDateTime	with(TemporalField field, long newValue)

LocalDateTime	withDayOfMonth(int dayOfMonth)

LocalDateTime	withDayOfYear(int dayOfYear)

LocalDateTime	withHour(int hour)

LocalDateTime	withMinute(int minute)

LocalDateTime	withMonth(int month)

LocalDateTime	withNano(int nanoOfSecond)

LocalDateTime	withSecond(int second)

LocalDateTime	withYear(int year)

看代码:

import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.temporal.ChronoField;

/**
 * @Auther: www.itzhimei.com
 * @Description:
 */
public class WithMethod {

    public static void main(String[] args) {
        LocalDateTime localDateTime = LocalDateTime.of(2021,1,5,15,32,55);
        //修改分别按照年月日时分秒纳秒修改
        System.out.println(localDateTime.withYear(2022));
        System.out.println(localDateTime.withMonth(5));
        System.out.println(localDateTime.withDayOfMonth(20));
        System.out.println(localDateTime.withHour(8));
        System.out.println(localDateTime.withMinute(26));
        System.out.println(localDateTime.withSecond(10));
        System.out.println(localDateTime.withNano(666));

        //按照年月日修改
        LocalDateTime localDateTime1 = localDateTime.withYear(2022).withMonth(5).withDayOfMonth(6);
        System.out.println(localDateTime1);

        //按照一年中的某天进行时间修改
        LocalDateTime localDateTime2 = localDateTime.withYear(2025).withDayOfYear(355);
        System.out.println(localDateTime2);

        //基于一个时间枚举作为单位,来修改时间
        System.out.println(localDateTime.with(ChronoField.DAY_OF_MONTH, 3));

        //按照给定时间进行调整
        System.out.println(localDateTime.with(YearMonth.of(2020,5)));

    }
}

输出:

2022-01-05T15:32:55
2021-05-05T15:32:55
2021-01-20T15:32:55
2021-01-05T08:32:55
2021-01-05T15:26:55
2021-01-05T15:32:10
2021-01-05T15:32:55.000000666
2022-05-06T15:32:55
2025-12-21T15:32:55
2021-01-03T15:32:55
2020-05-05T15:32:55