1.java判断当前时间是否在指定时间段内
import java.time.LocalTime;
public class TimeRangeExample {
public static void main(String[] args) {
// 获取当前时间
LocalTime currentTime = LocalTime.now();
// 指定时间段的开始时间和结束时间
LocalTime startTime = LocalTime.of(8, 0); // 08:00
LocalTime endTime = LocalTime.of(18, 0); // 18:00
// 判断当前时间是否在指定时间段内
if (currentTime.isAfter(startTime) && currentTime.isBefore(endTime)) {
System.out.println("当前时间在指定时间段内");
} else {
System.out.println("当前时间不在指定时间段内");
}
}
}
2.使用 LocalTime.parse()
方法将时间字符串转换为 LocalTime
时间格式
import java.time.LocalTime;
public class TimeStringToLocalTimeExample {
public static void main(String[] args) {
String timeString = "12:30:45"; // 时间字符串,格式为HH:mm:ss
// 将时间字符串转换为LocalTime时间格式
LocalTime localTime = LocalTime.parse(timeString);
System.out.println("时间字符串转换后的LocalTime时间格式为: " + localTime);
}
}
3.获取当前时间的一周起止日期
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class WeekRangeExample {
public static void main(String[] args) {
// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 获取当前日期所在周的起始日期和结束日期
LocalDate startDate = currentDate.with(TemporalAdjusters.previousOrSame(java.time.DayOfWeek.MONDAY));
LocalDate endDate = currentDate.with(TemporalAdjusters.nextOrSame(java.time.DayOfWeek.SUNDAY));
System.out.println("当前日期所在周的起始日期:" + startDate);
System.out.println("当前日期所在周的结束日期:" + endDate);
}
}
4.获取当前日期所在的年月
import java.time.LocalDate;
public class YearMonthExample {
public static void main(String[] args) {
// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 获取当前日期所在的年月
int currentYear = currentDate.getYear();
int currentMonth = currentDate.getMonthValue();
System.out.println("当前日期所在的年:" + currentYear);
System.out.println("当前日期所在的月:" + currentMonth);
}
}
5.判断日期的星期几
DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
System.out.println(dayOfWeek); // 输出星期几的枚举值
6.日期的加减运算
LocalDate newDate = currentDate.plusDays(7); // 加7天
LocalDate newDate = currentDate.minusMonths(1); // 减1个月
7.判断日期的先后
boolean isBefore = currentDate.isBefore(specificDate);
boolean isAfter = currentDate.isAfter(specificDate);
boolean isEqual = currentDate.isEqual(specificDate);
8.获取日期的一些特殊值
int dayOfYear = currentDate.getDayOfYear(); // 当年的第几天
int lengthOfMonth = currentDate.lengthOfMonth(); // 当月的天数
boolean isLeapYear = currentDate.isLeapYear(); // 是否是闰年
9.获取今日所在周的起始、截止日期
LocalDate now = LocalDate.now();
LocalDate start = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
LocalDate end = now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));