实体对象
@Data
@TableName("service_date")
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value = "service_date对象", description = "日期状态查询表")
public class ServiceDate {
/**
* 主键
*/
@TableId(type = IdType.AUTO)
@ApiModelProperty(value = "主键")
private Integer id;
/**
* yy-MM-dd HH:mm:ss
*/
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "yy-MM-dd HH:mm:ss")
private Date dateTime;
/**
* yy-MM-dd
*/
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd")
@DateTimeFormat(pattern = "yyyy-MM-dd")
@ApiModelProperty(value = "yy-MM-dd")
private Date date;
/**
* 0:工作日,1 双休日,2节假日,4 调休日
*/
@ApiModelProperty(value = "0:工作日,1 双休日,2节假日,4 调休日")
private Integer type;
/**
* one
*/
@ApiModelProperty(value = "one")
private String one;
/**
* two
*/
@ApiModelProperty(value = "two")
private String two;
/**
* three
*/
@ApiModelProperty(value = "three")
private String three;
}
传入年份,即可初始化本年度的所有日期入库,周六周日做出标记
/**
* 初始化当年日期,和周六周末
*/
public void initDate(String year) {
try {
// 拿到当年中的所有日期
List<String> dateList = new ArrayList<>();
for (int i = 1; i <= 12; i++) {
dateList.addAll(getDayByMonth(i, year));
}
dateList = dateList.stream().distinct().collect(Collectors.toList());
// set 日期
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
// 添加当年所有日期数据
for (String date : dateList) {
ServiceDate serviceDate = new ServiceDate();
serviceDate.setDate(DateFormat.getDateInstance().parse(date));
serviceDate.setDateTime(DateFormat.getDateInstance().parse(date));
Calendar calendar = Calendar.getInstance();
calendar.setTime(simpleDateFormat.parse(date));
// index 值为 7 时 是周六 值为 1 时是末, 美国周六是一周的最后一天,周日是一周的最后一天
int index = calendar.get(Calendar.DAY_OF_WEEK);
if (index == 1 || index == 7) {
serviceDate.setType(1);
} else {
serviceDate.setType(0);
}
this.baseMapper.insert(serviceDate);
}
} catch (Exception e) {
log.error("日期初始化错误");
e.printStackTrace();
}
}
根据年份和月份,获取当月的所有日期,当月不满31天,会有重复数据,上面逻辑有去重
// 根据年份和月份获取当月的所有日期
public static List<String> getDayByMonth(int month, String year) {
List<String> data = new ArrayList<>();
try {
Calendar c = Calendar.getInstance();
// 获取当前的年份
// int year = c.get(Calendar.YEAR);
// 获取本月的总天数
int dayCount = c.getActualMaximum(Calendar.DAY_OF_MONTH);
// 定义时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 开始日期为当前年月拼接1号
Date startDate = sdf.parse(year + "-" + month + "-01");
// 结束日期为当前年月拼接该月最大天数
Date endDate = sdf.parse(year + "-" + month + "-" + dayCount);
// 设置calendar的开始日期
c.setTime(startDate);
// 当前时间小于等于设定的结束时间
while (c.getTime().compareTo(endDate) <= 0) {
String time = sdf.format(c.getTime());
data.add(time);
// 当前日期加1
c.add(Calendar.DATE, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return data;
}