java中有关于时间格式以及定时器遇到的问题
时间格式
这个是通过Calendar 做时间滚动
//开始时间yyyy-MM-dd HH:mm:ss @Value("${StartTime}") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date startTime; //结束时间yyyy-MM-dd HH:mm:ss @Value("${EntTime}") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date endTime; //累加时间戳 startTime = endTime; // 获取Calendar对象并以传进来的时间为准 Calendar calendar = Calendar.getInstance(); calendar.setTime(endTime); // 将现在的时间滚动固定时长,转换为Date类型赋值 calendar.add(Calendar.MONTH, 5); // 转换为Date类型再赋值 Date time = calendar.getTime(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = formatter.format(time); try { endTime=formatter.parse(format); } catch (ParseException e) { e.printStackTrace(); } //或者通过这种时间戳 long startTimeTemp = startTime.getTime(); startTime = endTime; long endTimeTemp = startTimeTemp + 30*60 * 1000; endTime = new Date(endTimeTemp); //这个通过当前时间做滚动,配合定时器使用 startTime = endTime; endTime = new Date();
处理文件名的日期,存储到字段中。如果对存入时间格式有要求,需要两个SimpleDateFormat
//处理日期 Dto Dto = new Dto(); // picUrl = "../../202209151430000001.jpg" String str1 = picUrl.substring(picUrl.lastIndexOf("/")+1); String str2 = str1.substring(0,14); //SimpleDateFormat格式化 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMddHHmmss"); //先转为Date类型 Date date = new Date(formatter1.parse(str2).getTime()); //将"yyyyMMddHHmmss"的时间格式化为"yyyy-MM-dd HH:mm:ss"字符串,并转成时间类型 String lastTime = formatter.format(date); Date time = formatter.parse(lastTime) Dto.setCreateTime(time);
定时器
定时器要注意,业务处理时间如果太长了,会超过定时器设置时间,导致业务中止重启一遍,注意加事务抛异常。
@Scheduled(cron = "0/10 * * * * ?") 通过cron表达式定时
在定时器里面调用业务层代码
@Autowired private TestService testService; //定时器注解 @Scheduled(cron = "0 0/5 * * * ?") @PostConstruct private void ScheduledTaskTest(){ testService.test(); }
@PostConstruct 程序一启动就运行代码,可以配合一下@Scheduled使用,做到程序启动就先执行一次
@PostConstruct @Scheduled(cron = "0/10 * * * * ?") private void scheduledTaskTest(){ }
DateUtil
import com.alibaba.fastjson.JSON; import org.apache.commons.lang3.time.DateFormatUtils; import java.lang.management.ManagementFactory; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.time.Duration; import java.time.Instant; import java.util.*; public class DateUtil extends org.apache.commons.lang3.time.DateUtils { public static int getMondayPlus() { Calendar cd = Calendar.getInstance(); // 获得今天是一周的第几天,星期日是第一天,星期一是第二天 int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK); if (dayOfWeek == 1) { return -6; } else { return 2 - dayOfWeek; } } // 获取这个星期开始和结束的时间戳 public static List<Date> weekUtil(){ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); int mondayPlus = getMondayPlus(); GregorianCalendar currentDate = new GregorianCalendar(); currentDate.add(GregorianCalendar.DATE, mondayPlus); Date monday = currentDate.getTime(); String time=dateFormat.format(monday); //System.out.println(time); Date date = null; try { date = dateFormat.parse(time); } catch (Exception e) { e.printStackTrace(); } //System.out.println(date.getTime()); Date monDate=date; Date nextMon=new Date(monDate.getTime()+86400000*7-1000); List<Date> dateList=new LinkedList<>(); dateList.add(monDate); dateList.add(nextMon); System.out.println(JSON.toJSON(dateList)); return dateList; } /** * 获取当月开始时间戳 * * @return */ public static Date getMonthStartTime() { Calendar calendar = Calendar.getInstance();// 获取当前日期 calendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.YEAR, 0); calendar.add(Calendar.MONTH, 0); calendar.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天 calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); } /** * 获取当月的结束时间戳 * * @return */ public static Date getMonthEndTime() { Calendar calendar = Calendar.getInstance();// 获取当前日期 calendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.YEAR, 0); calendar.add(Calendar.MONTH, 0); calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));// 获取当前月最后一天 calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); calendar.set(Calendar.MILLISECOND, 999); return calendar.getTime(); } // 获取每月开始和结束的时间戳 public static List<Date> monthUtil(){ List<Date> dateList=new LinkedList<>(); dateList.add(getMonthStartTime()); dateList.add(getMonthEndTime()); //System.out.println(dateList); return dateList; } public static Date parseDate(String dateStr){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return simpleDateFormat.parse(dateStr,new ParsePosition(0)); } public static Date currentDate(){ Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY,0); calendar.set(Calendar.MINUTE,0); calendar.set(Calendar.SECOND,0); return calendar.getTime(); } public static void main(String[] args) { weekUtil(); monthUtil(); } public static Long getDateMinuteSpan(Date sDate,Date eDate){ Instant sinstant = sDate.toInstant(); Instant einstant = eDate.toInstant(); Long min = Duration.between(sinstant,einstant).toMinutes(); System.out.println("getDateMinuteSpan:"+min); return min; } public static Long timeDiff(Long sDate,Long eDate){ Long diff = (eDate - sDate)/1000/60; return diff; } public static Long getDateSecondSpan(Date sDate,Date eDate){ Instant sinstant = sDate.toInstant(); Instant einstant = eDate.toInstant(); Long sec = Duration.between(sinstant,einstant).toMillis(); System.out.println("getDateMinuteSpan:"+sec); return sec; } public static String YYYY = "yyyy"; public static String YYYY_MM = "yyyy-MM"; public static String YYYY_MM_DD = "yyyy-MM-dd"; public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"}; /** * 获取当前Date型日期 * * @return Date() 当前日期 */ public static Date getNowDate() { return new Date(); } /** * 获取当前日期, 默认格式为yyyy-MM-dd * * @return String */ public static String getDate() { return dateTimeNow(YYYY_MM_DD); } public static final String getTime() { return dateTimeNow(YYYY_MM_DD_HH_MM_SS); } public static final String dateTimeNow() { return dateTimeNow(YYYYMMDDHHMMSS); } public static final String dateTimeNow(final String format) { return parseDateToStr(format, new Date()); } public static final String dateTime(final Date date) { return parseDateToStr(YYYY_MM_DD, date); } public static final String parseDateToStr(final String format, final Date date) { return new SimpleDateFormat(format).format(date); } public static final Date dateTime(final String format, final String ts) { try { return new SimpleDateFormat(format).parse(ts); } catch (ParseException e) { throw new RuntimeException(e); } } /** * 日期路径 即年/月/日 如2018/08/08 */ public static final String datePath() { Date now = new Date(); return DateFormatUtils.format(now, "yyyy/MM/dd"); } /** * 日期路径 即年/月/日 如20180808 */ public static final String dateTime() { Date now = new Date(); return DateFormatUtils.format(now, "yyyyMMdd"); } /** * 日期型字符串转化为日期 格式 */ public static Date parseDate(Object str) { if (str == null) { return null; } try { return parseDate(str.toString(), parsePatterns); } catch (ParseException e) { return null; } } /** * 获取服务器启动时间 */ public static Date getServerStartDate() { long time = ManagementFactory.getRuntimeMXBean().getStartTime(); return new Date(time); } /** * 计算两个时间差 */ public static String getDatePoor(Date endDate, Date nowDate) { long nd = 1000 * 24 * 60 * 60; long nh = 1000 * 60 * 60; long nm = 1000 * 60; // long ns = 1000; // 获得两个时间的毫秒时间差异 long diff = endDate.getTime() - nowDate.getTime(); // 计算差多少天 long day = diff / nd; // 计算差多少小时 long hour = diff % nd / nh; // 计算差多少分钟 long min = diff % nd % nh / nm; // 计算差多少秒//输出结果 // long sec = diff % nd % nh % nm / ns; return day + "天" + hour + "小时" + min + "分钟"; } /** * 根据日期相加减天数 */ public static Date addDate(Date date, int days){ Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DATE, days); return calendar.getTime(); } /** * 时间戳转成本机时区的格林尼治时间 * @return */ public static Long dateLongToiso8601() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Calendar calendar = Calendar.getInstance(); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // 设置时区为GMT //String dateStr = sdf.format(calendar.getTime()); return calendar.getTime().getTime(); } /** * 时间加减分钟 * @param startDate 要处理的时间,Null则为当前时间 * @param minutes 加减的分钟 * @return */ public static Date dateAddMinutes(Date startDate, int minutes) { if (startDate == null) { startDate = new Date(); } Calendar c = Calendar.getInstance(); c.setTime(startDate); c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + minutes); return c.getTime(); } /** * 时间加减秒数 * @param startDate 要处理的时间,Null则为当前时间 * @param seconds 加减的秒数 * @return */ public static Date dateAddSeconds(Date startDate, int seconds) { if (startDate == null) { startDate = new Date(); } Calendar c = Calendar.getInstance(); c.setTime(startDate); c.set(Calendar.SECOND, c.get(Calendar.SECOND) + seconds); return c.getTime(); } }