本来是这样写的,正常用没问题,但是会出现00:00:00的情况
Date date = new Date();
List empCouponDTOS = couponInfoDTOS.stream()
.filter(couponInfoDTO -> couponInfoDTO.getStatus().equals(CommonKey.CONSTANT_1) &&
date.after(couponInfoDTO.getReceiveBeginDate()) &&
date.before(couponInfoDTO.getReceiveEndDate()))
.flatMap(couponInfoDTO -> {
Integer validityDays = couponInfoDTO.getValidityDays();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, validityDays);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
Date endDate = calendar.getTime();
return IntStream.range(0, couponNumMap.get(couponInfoDTO.getCouponId()))
.mapToObj(i -> {
EmpCouponDTO dto = new EmpCouponDTO();
dto.setEmpCode(userCode);
dto.setCouponId(couponInfoDTO.getCouponId());
dto.setCouponCode(SnowFlake.generateCouponCode());
dto.setStatus(CommonKey.CONSTANT_1);
dto.setValidBeginDate(date);
dto.setValidEndDate(endDate);
dto.setCreateDate(date);
dto.setUpdateDate(date);
return dto;
});
}).collect(Collectors.toList());
后面通过工具类改成了转换成字符串,再转换为时间
public static void main(String[] args) {
Date date = new Date();Calendar calendar = Calendar.getInstance();
int validityDays = 3;
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, validityDays);
Date endDate = calendar.getTime();
String strDate = DateUtil.DateToString(endDate, DEADLINE__HH_MM_SS);
try {
Date strToDate = DateUtil.getStrToDate(strDate, YEAR_MONTH_DAY_HH_MM_SS);
System.out.println(strToDate);
} catch (Exception e) {
e.printStackTrace();
}
}
DateUtil
package cn.homed.common.utils;
import cn.homed.common.constant.ResultCode;
import cn.homed.common.exception.BizException;
import org.apache.commons.lang3.StringUtils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;
public class DateUtil {
public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static final String YEAR_MONTH_DAY = "yyyy-MM-dd";
public static final String YEAR_MONTH = "yyyy年MM月";
/**
* yyyy-MM-dd HH:mm:ss格式
*/
public static final String YEAR_MONTH_DAY_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String DEADLINE__HH_MM_SS = "yyyy-MM-dd 23:59:59";
/**
* 格式化指定格式的Date
*
* @param date
* @param pattern
* @return
*/
public static String DateToString(Date date, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(YEAR_MONTH_DAY);
if (pattern != null) {
sdf.applyPattern(pattern);
}
return sdf.format(date);
}
/**
* 时区字符换转换Date
* @param timeStr
* @return
* @throws ParseException
*/
public static Date zoneTimetoDate(String timeStr) {
DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
OffsetDateTime dateTime = OffsetDateTime.parse(timeStr, formatter);
return Date.from(dateTime.toInstant());
}
/**
* 获取后nextDays天的Date对象
*
* @param date
* @param nextDays
* @return
*/
public static Date nextDays(Date date, int nextDays) {
GregorianCalendar c1 = new GregorianCalendar();
c1.setTime(date);
GregorianCalendar cloneCalendar = (GregorianCalendar) c1.clone();
cloneCalendar.add(Calendar.DATE, nextDays);
return cloneCalendar.getTime();
}
/**
* 获取后nextDays天的String对象
*
* @param date
* @param nextDays
* @return
*/
public static String nextDaysToString(Date date, int nextDays, String pattern) {
return DateToString(nextDays(date, nextDays), pattern);
}
/**
* 得到当前时间,输出默认格式:yyyy-MM-dd HH:mm:ss
*
* @return Date
*/
public static Date now() {
return new GregorianCalendar().getTime();
}
public static String getNowString() {
SimpleDateFormat sdf = new SimpleDateFormat(YEAR_MONTH_DAY_HH_MM_SS);
Date date = new GregorianCalendar().getTime();
return sdf.format(date);
}
public static String getNowString(String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date = new GregorianCalendar().getTime();
return sdf.format(date);
}
public static String getNowString14() {
SimpleDateFormat sdf = new SimpleDateFormat(YYYYMMDDHHMMSS);
Date date = new GregorianCalendar().getTime();
return sdf.format(date);
}
/**
* //计算给开始日期 结束日期 的间隔秒钟数 yyyy-MM-dd
*
* @param start_date
* @param end_date
* @param flag 1: 秒 2:天数
* @return
* @throws Exception
*/
public static int getSecondLength(String start_date, String end_date, int flag) throws Exception {
//一天等于多少秒:24*3600*1000
if (flag == 2) {
Date fromDate = getStrToDate(start_date, YEAR_MONTH_DAY); //开始日期
Date toDate = getStrToDate(end_date, YEAR_MONTH_DAY); //结束日期
long from = fromDate.getTime();
long to = toDate.getTime();
return (int) (to - from) / 1000;
} else {
Date fromDate = getStrToDate(start_date, YYYYMMDDHHMMSS); //开始日期
if (end_date.length() >= 14) {
end_date = end_date.substring(0, 14);
}
if (end_date.length() == 10) {
end_date = end_date.substring(0, 4) + end_date.substring(5, 7) + end_date.substring(8, 10) + "240000";
}
if (end_date.length() == 8) {
end_date = end_date.concat("240000");
}
Date toDate = getStrToDate(end_date, YYYYMMDDHHMMSS); //结束日期
long from = fromDate.getTime();
long to = toDate.getTime();
return (int) ((to - from) / 1000);
}
}
/**
* 获取二日期相差天数
* @param startDate
* @param endDate
* @return
*/
public static int getDifferDay(Date startDate, Date endDate){
if(null==startDate||null==endDate){
return 0;
}
Long num=endDate.getTime()-startDate.getTime();
return (int)(num/24/60/60/1000);
}
/**
* 获取指定时间的前后指定天数的时间点
* @param date 需要加减时间的日期
* @param days 天数
* @return 加减对应时间后的日期
* 七天:(7 * 24 * 60 * 60 * 1000)
* 指定时间之前 为负数 指定时间之后为正数
* */
public static Date subtractTime(Date date,int days){
try {
int amount=days* 24 * 60 * 60 * 1000;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strTime = sdf.format(date.getTime() + amount);
Date time = sdf.parse(strTime);
return time;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Date getStrToDate(String date, String fomtter) throws Exception {
DateFormat df = new SimpleDateFormat(fomtter);
return df.parse(date);
}
/**
* 格式化指定格式的Date
*
* @param date
* @return
*/
public static String format(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(YEAR_MONTH_DAY_HH_MM_SS);
return sdf.format(date);
}
/**
* 格式化指定格式的Date
*
* @param date
* @param pattern
* @return
*/
public static String toString(Date date, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(YEAR_MONTH_DAY_HH_MM_SS);
sdf.applyPattern(pattern);
return sdf.format(date);
}
/**
* 得到指定格式的Date
*
* @param pattern 格式,请参考DateFormator类
* @return Date
*/
public static String now(String pattern) {
Date date = now();
String str = toString(date, pattern);
return str;
}
/**
* 获取指定日期之间的所有年月
*/
public static List getMonthBetween(String minDate, String maxDate) {
ArrayList result = new ArrayList();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
Calendar min = Calendar.getInstance();
Calendar max = Calendar.getInstance();
try {
min.setTime(sdf.parse(minDate));
max.setTime(sdf.parse(maxDate));
} catch (ParseException e) {
LogUtils.error("getMonthBetween解析日期异常", e);
}
min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
Calendar curr = min;
while (curr.before(max)) {
result.add(sdf.format(curr.getTime()));
curr.add(Calendar.MONTH, 1);
}
return result;
}
/**
* 获取指定日期之间的所有年
*/
public static List getYearBetween(String minDate, String maxDate) {
ArrayList result = new ArrayList();
if (StringUtils.isNotBlank(minDate) && StringUtils.isNotBlank(maxDate)) {
int min = Integer.parseInt(minDate);
int max = Integer.parseInt(maxDate);
if (max >= min) {
result.add(minDate);
int temp = min;
while (max > temp) {
temp = temp + 1;
result.add(String.valueOf(temp));
}
}
}
return result;
}
/**
* 获取之前最近年份
*
* @return
*/
public static String getPreYear() {
Calendar date = Calendar.getInstance();
return Integer.parseInt(String.valueOf(date.get(Calendar.YEAR))) - 1 + "";
}
/**
* 获取之前年份
*
* @return
*/
public static String getPreYear(int variable) {
Calendar date = Calendar.getInstance();
return Integer.parseInt(String.valueOf(date.get(Calendar.YEAR))) - variable + "";
}
/**
* String -> String
*/
public static String formateTimeStringToString(String time, String pattern) {
String result = "";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
result = format.format(format.parse(time));
} catch (ParseException e) {
LogUtils.error("formateStringTime()解析日期异常", e);
}
return result;
}
/**
* 获取上个月最后一天
*
* @param
* @return
*/
public static long getMonthsDay() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
long ts = (calendar.getTime().getTime()) / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
return ts / 1000;
}
/**
* 获取当前年第一天日期
*
* @return Date
*/
public static long getYearFirst(int variable) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -variable);
calendar.add(Calendar.MONTH, -1);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date currYearFirst = calendar.getTime();
long ts = (currYearFirst.getTime()) / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
return ts / 1000;
}
/**
* 获取过去连续月份
*
* @param month
* @return
*/
public static List getLastMonth(int month) {
List list = new ArrayList<>(10);
LocalDate today = LocalDate.now();
for (long i = 1L; i <= month; i++) {
LocalDate localDate = today.minusMonths(i);
list.add(String.valueOf(localDate).substring(0, 7).replace("-", ""));
}
return list;
}
/**
* 获取过去连续月份
*
* @param year
* @return
*/
public static List getLastYear(int year, long timestamp, boolean flag) {
List list = new ArrayList<>(10);
if (flag) {
LocalDate today = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8)).toLocalDate();
for (long i = 0L; i < year; i++) {
LocalDate localDate = today.minusYears(i);
list.add(String.valueOf(localDate).substring(0, 4));
}
} else {
LocalDate today = LocalDate.now();
for (long i = 1L; i <= year; i++) {
LocalDate localDate = today.minusYears(i);
list.add(String.valueOf(localDate).substring(0, 4));
}
}
return list;
}
public static int getAge(LocalDate localDate) {
if (localDate == null){
return 0;
}
Calendar cal = Calendar.getInstance();
int yearNow = cal.get(Calendar.YEAR); //当前年份
int monthNow = cal.get(Calendar.MONTH); //当前月份
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
Date birthDay = Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
cal.setTime(birthDay);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH);
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
//计算整岁数
int age = yearNow - yearBirth;
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
if (dayOfMonthNow < dayOfMonthBirth) {
age--;//当前日期在生日之前,年龄减一
}
}else{
age--;//当前月份在生日之前,年龄减一
} } return age;
}
public static void checkDateOfBirth(LocalDate localDate) {
if (localDate == null){
return;
}
Calendar cal = Calendar.getInstance();
Date birthDay = Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
if (cal.before(birthDay)) { //出生日期晚于当前时间,无法计算
throw new BizException(ResultCode.DATEOFBIRTH_ERROR);
}
}
/**
* @param idCardNumber 根据身份证号码 获取出生年月
* @return {@link String}
*/
public static String getBirthdayFromIdCard(String idCardNumber) {
String birthday = idCardNumber.substring(6, 14);
String year = birthday.substring(0, 4);
String month = birthday.substring(4, 6);
String day = birthday.substring(6, 8);
return year + "-" + month + "-" + day;
}
}