import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;
public class DateRangeExamples {
public static void main(String[] args) {
// 获取当前日期和时间
LocalDateTime now = LocalDateTime.now();
// 获取当前周一的日期
LocalDateTime currentMonday = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
// 获取当前周五的日期
LocalDateTime currentFriday = now.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
// 打印当前周一到周日的日期
System.out.println("当前周一的日期: " + currentMonday.toLocalDate());
System.out.println("当前周日的日期: " + currentFriday.toLocalDate());
// 获取当月1号的日期
LocalDateTime firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
// 获取当月最后一天的日期
LocalDateTime lastDayOfMonth = now.with(TemporalAdjusters.lastDayOfMonth());
// 打印当月1号到月末的日期
System.out.println("当月1号的日期: " + firstDayOfMonth.toLocalDate());
System.out.println("当月末的日期: " + lastDayOfMonth.toLocalDate());
// 获取今年的起始日期
LocalDateTime firstDayOfYear = now.with(TemporalAdjusters.firstDayOfYear());
// 获取今年的最后一天
LocalDateTime lastDayOfYear = now.with(TemporalAdjusters.lastDayOfYear());
// 打印今年的起始日期和最后一天
System.out.println("今年的起始日期: " + firstDayOfYear.toLocalDate());
System.out.println("今年的最后一天: " + lastDayOfYear.toLocalDate());
}
}
使用javascript 实现类似效果
方法封装
function getDateRange(type) {
const now = new Date();
function getMonday(d) {
d = new Date(d);
d.setDate(d.getDate() - (d.getDay() + 6) % 7);
return d;
}
function getSunday(d) {
d = new Date(d);
d.setDate(d.getDate() + (7 - d.getDay()) % 7);
return d;
}
function formatISODate(date) {
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
return `${year}-${month}-${day}`;
}
let startDate, endDate;
switch (type) {
case 'week':
startDate = getMonday(now);
endDate = getSunday(now);
break;
case 'month':
// Start date is the first day of the current month
startDate = new Date(now.getFullYear(), now.getMonth(), 1);
// End date is the first day of the next month minus one day
endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);
break;
default:
throw new Error('Invalid type provided. Use "week" or "month".');
}
return [formatISODate(startDate), formatISODate(endDate)];
}
// 使用示例:
console.log(getDateRange('week')); // 输出当前周一和周日的日期范围
console.log(getDateRange('month')); // 输出当前月第一天和最后一天的日期范围
标准输出:
[ ‘2024-07-15’, ‘2024-07-21’ ]
[ ‘2024-07-01’, ‘2024-07-31’ ]