获取当周和上周的周一、周日时间

这篇博客提供了四个Java方法,用于获取当前周的周一和周日,以及上周一和周日的具体时间,格式化为'yyyy-MM-dd HH:mm:ss'。通过Calendar类设置日期并调整到一周的第一天(周日或周一),然后进行加减天数来实现目标日期的获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

获取当周和上周的周一、周日时间

获取当周的周一

public static String getFirstDay() {
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Calendar calendar = Calendar.getInstance();
	// 一周第一天为周日,所以这里+1
	calendar.setWeekDate(calendar.getWeekYrae(), calendar.get(Calendar.WEEK_of_year), 2);
	calendar.set(calendar.get(calendar.YEAR), calendar.get(Calendar.MONTH), calendar..get(calendar.DAY_OF_MONTH), 0, 0, 0);
	return sdf.format(calendar.getTime());
}

获取当周的周日

public static String getLastDay() {
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Calendar calendar = Calendar.getInstance();
	// 一周第一天为周日,所以这里下周一为第一天
	calendar.setWeekDate(calendar.getWeekYrae(), calendar.get(Calendar.WEEK_of_year) + 1, 1);
	calendar.set(calendar.get(calendar.YEAR), calendar.get(Calendar.MONTH), calendar..get(calendar.DAY_OF_MONTH), 23, 59, 59);
	return sdf.format(calendar.getTime());
}

获取上周一的时间

public static String getLastMonday() {
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Calendar calendar = Calendar.getInstance();
	// 设置周一为第一天
	calendar.setFirstDayOfWeek(Calendar.MONDAY);
	// 日期减去7天
	calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
	return sdf.format(calendar.getTime()) + " 00:00:00";
}

获取上周日的时间

public static String getLastSunday() {
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Calendar calendar = Calendar.getInstance();
	// 设置周一为第一天
	calendar.setFirstDayOfWeek(Calendar.MONDAY);
	// 日期减去7天
	calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
	return sdf.format(calendar.getTime()) + " 23:59:59";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值