- plusNanos(int offset):增加指定纳秒
减少相关的方法
-
minusYears(int offset):减少指定年
-
minusMonths(int offset):减少指定月
-
minusWeeks(int offset):减少指定周
-
minusDates(int offset):减少指定日
-
minusHours(int offset):减少指定时
-
minusMinuets(int offset):减少指定分
-
minusSeconds(int offset):减少指定秒
-
minusNanos(int offset):减少指定纳秒
@Test
public void test07() {
//增加时间量的方法 plusXXX系类的方法 返回的是一个新的日期对象
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
//可以给当前的日期增加时间量
LocalDateTime newDate = now.plusYears(1);
int year = newDate.getYear();
System.out.println(year);
System.out.println("================================");
//减去时间量的方法minusXXX 系列的方法 返回的是一个新的日期对象
LocalDate now1 = LocalDate.now();
System.out.println(now1);
LocalDate newDate2 = now1.minusDays(10);
int dayOfMonth = newDate2.getDayOfMonth();
System.out.println(dayOfMonth);
}
输出结果
2020-12-12T16:12:43.228
2021
================================
2020-12-12
2
[](
)指定年月日时分秒的方法
-
with(TemporalAdjuster adjuster):指定特殊时间
-
withYear(int year):指定年
-
withDayOfYear(int dayOfYear):指定日
-
withMonth(int month):指定月
-
withDayOfMonth(int dayOfMonth):指定日
@Test
public void test08() {
//指定某个日期的方法 with()方法
LocalDate now2 = LocalDate.now();
System.out.println(now2);
LocalDate localDate = now2.withYear(2014);
System.out.println(localDate);
// TemporalAdjusters工具类,提供了一些获取特殊日期的方法
LocalDate with = now2.with(TemporalAdjusters.firstDayOfMonth());
System.out.println(with);
LocalDate with1 = now2.with(TemporalAdjusters.firstDayOfNextMonth());
System.out.println(with1);
//获取这个月的第几个星期几是几号,比如 TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.FRIDAY)
// 代表的意思是这个月的第二个星期五是几号
LocalDate with2 = now2.with(TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.FRIDAY));
System.out.println(with2);
}
输出结果
2020-12-12
2014-12-12
2020-12-01
2021-01-01
2020-12-11
[](
)将日期格式化为字符串的方法
- format():格式化字符串
@Test
public void test03() {
//获取当前日期时分秒
LocalDateTime now = LocalDateTime.now();
//默认格式 年-月-日T时:分:秒
System.out.println(now);
//指定格式
DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
//传入格式
String dateStr = now.format(ofPattern);
System.out.println(dateStr);
}
输出结果
2020-12-12T16:06:12.705
2020年12月12日 16时06分12秒
[](
)解析字符串为日期时间的方法
-
paser(String str):将一个日期字符串解析成日期对象,注意字符串日期的写法的格式要正确,否则解析失败
-
paser(String str, DateTimeFormatter formatter):将字符串按照参数传入的格式进行解析
@Test
public void test06() {
//给出一个符合默认格式要求的日期字符串
String dateStr = "2020-01-01";
//把日期字符串解析成日期对象 如果日期字符串时年月日 解析时用 LocalDate
LocalDate parse = LocalDate.parse(dateStr);
System.out.println(parse);
System.out.println("===========================================");
//给出一个符合默认格式要求的 时分秒 字符串
String dateTimeStr = "14:20:30";
//把 时分秒 字符串解析成时分秒对象
LocalTime parse1 = LocalTime.parse(dateTimeStr);
System.out.println(parse1);
System.out.println("=========================================");
//给出一个符合默认格式要求的 日期时分秒 字符串
String str = "2018-12-12T14:20:30";
//把 日期时分秒 字符串解析成时分秒对象
LocalDateTime parse2