1.获取当前的时间
LocalDate now = LocalDate.now();//LocalDate
Date nowDate = DateUtils.getNowDate();//Date
2.获取当前时间所在的周的开始和结束时间
LocalDate startOfWeek = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
// 设置为本周的第一天(默认周日为第一天)
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
Date startOfWeek = calendar.getTime();
// 设置为本周的最后一天
calendar.add(Calendar.DAY_OF_WEEK, 6);
Date endOfWeek = calendar.getTime();
3.获取当前时间所在的月的开始和结束时间
LocalDate startOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth());
LocalDate endOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());
4.获取当前时间是这周/月/年的第几天、
DayOfWeek dayOfWeek = now.getDayOfWeek();
int dayOfMonth = now.getDayOfMonth();
int dayOfYear = now.getDayOfYear();
5.获取两个日期之间的天数
LocalDate date1 = LocalDate.of(2023, 12, 1);
LocalDate date2 = LocalDate.of(2023, 12, 31);
long daysBetween = ChronoUnit.DAYS.between(date1, date2);
6.获取当前的时间戳
long currentTimestamp = System.currentTimeMillis();
Date类已经不是很常用有些方法都失效了,推荐使用LocalDate和LocalDateTime来处理日期和时间。
7.根据年份去计算有多少周
int year = 2022; // 请替换为你要判断的年份
WeekFields weekFields = WeekFields.ISO;
LocalDate firstDayOfYear = LocalDate.of(year, 1, 1);
LocalDate lastDayOfYear = LocalDate.of(year, 12, 31);
int numWeeks = lastDayOfYear.get(weekFields.weekOfWeekBasedYear());
if (firstDayOfYear.get(weekFields.weekOfWeekBasedYear()) == 1) {
numWeeks += 1;
}
8.计算某个时间点是在今年的第多少周
WeekFields weekFields = WeekFields.of(Locale.getDefault());
int weekNumber = LocalDate格式的日期.get(weekFields.weekOfWeekBasedYear());
关于WeekFields.ISO 源码解释:
The ISO-8601 definition, where a week starts on Monday and the first week has a minimum of 4 days.Note that the first week may start in the previous calendar year.Note also that the first few days of a calendar year may be in the week-based-year corresponding to the previous calendar year.
ISO-8601是国际标准化组织(ISO)定义的日期和时间表示法的标准之一。这个标准定义了一年中的周数,其中一周的开始是星期一,一年中的第一个星期包含1月4日。这种定义方式使得一年中的周数和月份没有必然的对应关系。
可以使用它来获取一周的开始日期、结束日期,或者获取一年中的第几周等信息。