LocalDateTime设置时间的年、月、日、时、分、秒、纳秒
如何把String/Date转成LocalDateTime参考String、Date与LocalDate、LocalTime、LocalDateTime之间互转
String、Date、LocalDateTime、Calendar与时间戳之间互相转化参考String、Date、LocalDateTime、Calendar与时间戳之间互相转化
方法介绍
withYear(int year) 指定日期的年
withMonth(int month) 指定日期的月 范围:1-12
withDayOfMonth(int dayOfMonth) 指定日期是月中的第几天 范围:1 - 28/31
withDayOfYear(int dayOfYear) 指定日期是年中的第几天 范围:1 - 365/366
withHour(int hour) 指定日期的小时 范围:0 - 23
withMinute(int minute) 指定日期的分钟 范围:0 - 59
withSecond(int second) 指定日期的秒 范围:0 - 59
withNano(int nanoOfSecond) 指定日期中纳秒
具体使用
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;/*** 测试LocalDate* @author leishen*/
public class LocalDateTest {/*** LOCAL_DATE_TIME的时间格式*/private static final DateTimeFormatter LOCAL_DATE_TIME=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss ms ns");/*** DATE_TIME的时间格式*/private static final SimpleDateFormat DATE_TIME=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ms");public static void main(String[] args) {//系统默认时区ZoneId zoneId = ZoneId.systemDefault();//Date-->ZonedDateTimeZonedDateTime zonedDateTime = new Date().toInstant().atZone(zoneId);LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();System.out.println("localDateTime.format(LOCAL_DATE_TIME) = " + localDateTime.format(LOCAL_DATE_TIME));//withYear(int year) 指定日期的年localDateTime = localDateTime.withYear(2022);System.out.println("localDateTime.withYear(2022) = " +localDateTime.format(LOCAL_DATE_TIME));//withMonth(int month) 指定日期的月 范围:1-12localDateTime = localDateTime.withMonth(1);System.out.println("localDateTime.withMonth(1) = " + localDateTime.format(LOCAL_DATE_TIME));//withDayOfMonth(int dayOfMonth) 指定日期是月中的第几天 范围:1 - 28/31localDateTime = localDateTime.withDayOfMonth(1);System.out.println("localDateTime.withDayOfMonth(1) = " + localDateTime.format(LOCAL_DATE_TIME));//withDayOfYear(int dayOfYear) 指定日期是年中的第几天 范围:1 - 365/366localDateTime = localDateTime.withDayOfYear(60);System.out.println("localDateTime.withDayOfYear(60) = " + localDateTime.format(LOCAL_DATE_TIME));//withHour(int hour) 指定日期的小时 范围:0 - 23localDateTime = localDateTime.withHour(23);System.out.println("localDateTime.withHour(23) = " + localDateTime.format(LOCAL_DATE_TIME));//withMinute(int minute) 指定日期的分钟 范围:0 - 59localDateTime = localDateTime.withMinute(59);System.out.println("localDateTime.withMinute(59) = " + localDateTime.format(LOCAL_DATE_TIME));//withSecond(int second) 指定日期的秒 范围:0 - 59localDateTime =localDateTime.withSecond(59);System.out.println("localDateTime.withSecond(59) = " + localDateTime.format(LOCAL_DATE_TIME));//withNano(int nanoOfSecond) 指定日期中纳秒localDateTime = localDateTime.withNano(0);System.out.println("localDateTime.withNano(0) = " + localDateTime.format(LOCAL_DATE_TIME));Date date = Date.from(localDateTime.atZone(zoneId).toInstant());System.out.println("DATE_TIME.format(date) = " + DATE_TIME.format(date));}
}