String类型的日期循环输出

最近遇到一个棘手的问题
前端传过来两个String类型的日期值
需要后台循环得到每一天的数据,没数据的赋为0
坑爹的是库里面数据不一定每天都有
于是便有了下面的操作👇👇👇👇

//循环输出时间
public static void main(String[] args) throws ParseException {
	String start = "2021-07-01";
	String end = "2021-07-02";
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	Date dBegin = sdf.parse(start);
	Date dEnd = sdf.parse(end);
	List<Date> lDate = findDates(dBegin, dEnd);
	for (Date date : lDate) {
		System.out.println(sdf.format(date));
	}
}
public static List<Date> findDates(Date dBegin, Date dEnd) {
	List lDate = new ArrayList();
	lDate.add(dBegin);
	Calendar calBegin = Calendar.getInstance();
	// 使用给定的 Date 设置此 Calendar 的时间
	calBegin.setTime(dBegin);
	Calendar calEnd = Calendar.getInstance();
	// 使用给定的 Date 设置此 Calendar 的时间
	calEnd.setTime(dEnd);
	// 测试此日期是否在指定日期之后
	while (dEnd.after(calBegin.getTime())) {
	// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
		calBegin.add(Calendar.DAY_OF_MONTH, 1);
		lDate.add(calBegin.getTime());
	}
	return lDate;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好,以下是一个示例代码,可以循环输出每个月的日历表: ```java import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class CalendarPrinter { public static void main(String[] args) { int year = 2022; // 年份 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); for (int month = 1; month <= 12; month++) { // 循环输出每个月的日历表 LocalDate date = LocalDate.of(year, month, 1); int daysInMonth = date.lengthOfMonth(); // 获取本月天数 int firstDayOfWeek = date.getDayOfWeek().getValue(); // 获取本月第一天是星期几 String[][] calendar = new String[6][7]; // 存储本月日历表 int dayOfMonth = 1; for (int i = 0; i < 6; i++) { for (int j = 0; j < 7; j++) { if (i == 0 && j < firstDayOfWeek - 1) { calendar[i][j] = " "; // 填充空白 } else if (dayOfMonth > daysInMonth) { calendar[i][j] = " "; // 填充空白 } else { calendar[i][j] = String.format("%2d", dayOfMonth++); // 填充日期 } } } System.out.println(date.getMonth().toString() + " " + year); // 输出月份和年份 System.out.println("Mo Tu We Th Fr Sa Su"); // 输出星期标题 for (String[] row : calendar) { for (String day : row) { System.out.print(day + " "); } System.out.println(); } System.out.println(); } } } ``` 这段代码使用 Java 8 的日期时间 API,计算出每个月的天数和第一天是星期几,然后生成一个二维数组存储日历表,最后循环输出日历表。运行代码后,会输出 2022 年每个月的日历表。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值