我正在从数据库中获取周数和年份(使用函数DATE_PART('week',alarm_date -(interval '1 days')* 0)AS week,DATE_PART('year',alarm_date)AS yearNo,符合ISO标准),并根据周数和年份,我想计算用户提供的开始日期和结束日期之间的weekStartDate和weekEndDate,其中周开始日期例如{“startDate”:“2021-12-28”,“endDate”:“2022-01-06”,“weekStartDay”:“Sunday”}
private String getWeek(LocalDate startTime, LocalDate endTime, int yearNo, int weekNumber, int weekStartDay){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
// make it ISO compliant since postgres is using ISO time to calculate week number
cal.setMinimalDaysInFirstWeek(4);
cal.set(Calendar.YEAR, yearNo);
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
//ISO week starts on Monday and ends on Sunday
cal.set(Calendar.DAY_OF_WEEK, weekStartDay);// weekStartDay configurabale, as per
//user input Calendar.SUNDAY or Calendar.MONDAY or Calendar.TUEDAY; etc
String weekStartDate = sdf.format(cal.getTime());
cal.add(Calendar.DATE, 6);
String weekEndDate = sdf.format(cal.getTime());
LocalDate weekStart = LocalDate.of(Integer.valueOf(weekStartDate.substring(0, 4)),
Integer.valueOf(weekStartDate.substring(5, 7)), Integer.valueOf(weekStartDate.substring(8)));
if(weekStart.isBefore(startTime)) {
weekStart = startTime;
}
LocalDate weekEnd = LocalDate.of(Integer.valueOf(weekEndDate.substring(0, 4)),
Integer.valueOf(weekEndDate.substring(5, 7)), Integer.valueOf(weekEndDate.substring(8)));
if(weekEnd.isAfter(endTime)) {
weekEnd = endTime;
}
String weekStr = weekStart.toString()+"_"+weekEnd.toString();
return weekStr;
}
但是当weekStartDay福尔斯在上一年的最后一周时,它会给出weekStartDate和weekStartEnd的错误值,所以请建议我如何在java中设置年号
1条答案
按热度按时间xzlaal3s1#
Avinash,不是完整的答案,但与Tom提到的一致。自Java-8以来,可以使用许多方便的日期时间API。请根据您可能需要的确切逻辑自由定制此方法