失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 时间工具类 Instant date LocalDate String LocalDateTime 相互转换

时间工具类 Instant date LocalDate String LocalDateTime 相互转换

时间:2023-10-19 11:20:17

相关推荐

时间工具类 Instant date LocalDate String LocalDateTime 相互转换

public final class TimeUtil {private static final Logger LOGGER = LoggerFactory.getLogger(TimeUtil.class);private TimeUtil() {}/*** 获取当前时间(系统时间)距离特定时间(如18:00:00)的间隔,结果可能为正,亦可为负* 间隔 >=0: 表示当前时间未到达(或刚好到达)设定的时间* 间隔 <0: 表示当前时间已超过设定的时间* 有异常时抛出** @param time 字符串形式的时间,如 09:00:00 (不能写作 9:00:00)* @return long*/public static long getTimeDiffWithMills(String time) {try {// HH:mm:ssDateTimeFormatter localTimeFormatter = DateTimeFormatter.ofPattern(ConstantUtil.DATE_TIME_FORMAT_GENERAL_INFO);LocalTime planTime = LocalTime.parse(time, localTimeFormatter);LocalTime now = LocalTime.now();return Duration.between(now, planTime).toMillis();} catch (Exception e) {LOGGER.error("error message: 获取当前时间(系统时间)距离特定时间 <{}> 的间隔异常,原因是 <{}>", time, String.valueOf(e));throw new BusinessException(SystemErrorCode.DATE_CONVERT_FAILED);}}/*** 依据设定时间及其任务执行类型获取调整后的监听时间** @param time String 字符串形式的时间,如 09:00:00 (不能写作 9:00:00)* @param taskExecuteType AnalysisEnumEntity.TaskExecuteType 任务执行类型* @return long 调整后的毫秒时间*/public static long getAdjustedTimeDiffWithMillsByType(String time, AnalysisEnumEntity.TaskExecuteType taskExecuteType) {try {long initialDiff = getTimeDiffWithMills(time);switch (taskExecuteType) {// 定时执行case TASK_EXECUTE_TYPE_TIMED:if (initialDiff >= 0) {return initialDiff;} else {return initialDiff + ConstantUtil.ONE_DAY_IN_MILLISECONDS;}// 立即执行case TASK_EXECUTE_TYPE_IMMEDIATELY:return 0;default:LOGGER.error("error message: 暂不支持的任务执行类型 <{}>", taskExecuteType.getLabel());return 0;}} catch (Exception e) {LOGGER.error("error message: 依据任务类型 <{}> 获取调整后毫秒时间异常,原因是 <{}>", taskExecuteType.getLabel(), String.valueOf(e));throw new BusinessException(SystemErrorCode.DATE_CONVERT_FAILED);}}public static long getTime(String time) {DateFormat dateFormat = new SimpleDateFormat(ConstantUtil.DATE_TIME_FORMAT_GENERAL_YEAR);try {Date curDate = dateFormat.parse(time);return curDate.getTime() - System.currentTimeMillis();} catch (ParseException e) {LOGGER.error("error message: 时间转换出错,原因是 <{}>", String.valueOf(e));return 0;}}/*** 将 Instant 时间转换为 Date** @param instant Instant* @return Date* @throws BusinessException 转换异常*/public static Date instantToDate(Instant instant) throws BusinessException {try {return new Date(instant.toEpochMilli());} catch (Exception e) {LOGGER.error("error message: Instant 时间转换为 Date,失败,原因", e);throw new BusinessException(SystemErrorCode.DATE_CONVERT_FAILED);}}public static long getAdjustedTime(String time, AnalysisEnumEntity.TaskExecuteType taskExecuteType) {long initialDiff = getTime(time);switch (taskExecuteType) {// 定时执行case TASK_EXECUTE_TYPE_TIMED:if (initialDiff >= 0) {return initialDiff;} else {return initialDiff + ConstantUtil.ONE_DAY_IN_MILLISECONDS;}// 立即执行case TASK_EXECUTE_TYPE_IMMEDIATELY:return 0;default:return 0;}}/*** 将 unix 时间戳转换为 相应时区时间* 注意:当发生异常时,返回空字符串,未抛出异常** @param instant Instant Instant 时间* @param zoneIdType SystemEnumEntity.ZoneIdType 自定义时区类型* @return String*/public static String instantToString(Instant instant, SystemEnumEntity.ZoneIdType zoneIdType) {if (null == instant || null == zoneIdType) {LOGGER.debug("debug message: Instant 时间 <{}> 或 时区信息 <{}> 无效", instant, zoneIdType);return ConstantUtil.SPECIAL_CHARACTER_EMPTY;}try {DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(ConstantUtil.DATE_TIME_FORMAT_GENERAL).withZone(ZoneId.of(zoneIdType.getLabel()));return dateTimeFormatter.format(instant);} catch (Exception e) {LOGGER.error("error message: Instant 时间 <{}> 转换为特定字符串格式时间异常,原因是 <{}>", instant, String.valueOf(e));return ConstantUtil.SPECIAL_CHARACTER_EMPTY;}}/*** 将日期格式形如 yyyy-MM-dd HH:mm:ss 的字符串转为 Instant格式形如yyyy-MM-ddTHH:mm:ssZ 的字符串** @param dateTime String 日期格式形如 yyyy-MM-dd HH:mm:ss 的字符串* @return Instant格式形如yyyy-MM-ddTHH:mm:ssZ 的字符串* @throws BusinessException 日期转换异常*/public static String dateStringToInstantString(String dateTime) throws BusinessException {try {dateTime = dateTime.toUpperCase();if (dateTime.contains("T") && dateTime.contains("Z")) {return dateTime;}Instant instant = TimeUtil.stringToInstant(dateTime, SystemEnumEntity.ZoneIdType.ZONE_ID_TYPE_UTC, false);return instant.toString();} catch (Exception e) {LOGGER.error("error message: 日期时间 <{}> 转换为 Instant 时间异常,原因是 <{}>", dateTime, String.valueOf(e));throw new BusinessException(SystemErrorCode.DATE_CONVERT_FAILED);}}/*** 将 String 时间转换为 相应时区下的时间戳** @param dateTime String* @param zoneIdType SystemEnumEntity.ZoneIdType* @param dateTimeFormatFlag boolean* True-Instant格式的字符串,形如"-11-25T14:00:13Z"* False-非Instant格式的字符串,形如"-11-25 14:00:13"* @return Instant* @throws BusinessException 抛出异常*/public static Instant stringToInstant(String dateTime,SystemEnumEntity.ZoneIdType zoneIdType,boolean dateTimeFormatFlag) throws BusinessException {if (StringUtil.isEmpty(dateTime) || null == zoneIdType) {LOGGER.error("error message: 日期时间 <{}> 或 时区信息 <{}> 无效", dateTime, zoneIdType);throw new BusinessException(GuiErrorCode.ACCESS_PARAMETER_INVALID);}try {if (dateTimeFormatFlag) {return LocalDateTime.ofInstant(Instant.parse(dateTime), ZoneId.of(zoneIdType.getLabel())).toInstant(ZoneOffset.UTC);} else {DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(ConstantUtil.DATE_TIME_FORMAT_GENERAL);LocalDateTime localDateTime = LocalDateTime.parse(dateTime, dateTimeFormatter);return localDateTime.atZone(ZoneId.of(zoneIdType.getLabel())).toInstant();}} catch (Exception e) {LOGGER.error("error message: 字符串格式时间 <{}> 转换为 Instant 异常,原因是 <{}>", dateTime, String.valueOf(e));throw new BusinessException(SystemErrorCode.DATE_CONVERT_FAILED);}}/*** 将 Instant 时间转换为 LocalDateTime** @param instant Instant Instant 时间* @param zoneIdType SystemEnumEntity.ZoneIdType 时区信息* @return LocalDateTime* @throws BusinessException 转换异常*/public static LocalDateTime instantToLocalDateTime(Instant instant, SystemEnumEntity.ZoneIdType zoneIdType) throws BusinessException {try {return LocalDateTime.ofInstant(instant, ZoneId.of(zoneIdType.getLabel()));} catch (Exception e) {LOGGER.error("error message: Instant 时间 <{}> 转换为 LocalDateTime 异常,原因是 <{}>", instant, String.valueOf(e));throw new BusinessException(SystemErrorCode.DATE_CONVERT_FAILED);}}/*** 将日期转为特定格式的字符串日期** @param date Date 待转换的日期* @param formatString 时间格式字符串* @param zoneIdType SystemEnumEntity.ZoneIdType 时区信息* @return String 字符串格式的时间* @throws BusinessException 自定义异常*/public static String dateToString(Date date, String format, SystemEnumEntity.ZoneIdType zoneIdType) throws BusinessException {try {DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);return dateTimeFormatter.format(date.toInstant().atZone(ZoneId.of(zoneIdType.getLabel())).toLocalDate());} catch (Exception e) {LOGGER.error("error message: 日期 <{}> 转换为 String 格式 <{}> 日期时间异常,原因是 <{}>", date, format, String.valueOf(e));throw new BusinessException(SystemErrorCode.DATE_CONVERT_FAILED);}}/*** 将特定格式的字符串日期转为日期形式** @param str Date* @param dateFormat String* @return String* @throws BusinessException 自定义异常*/public static LocalDate stringToLocalDate(String str, String dateFormat) throws BusinessException {try {DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormat);return LocalDate.parse(str, dateTimeFormatter);} catch (Exception e) {LOGGER.error("error message: String 格式日期 <{}> 转换为 LocalDate 格式 <{}> 日期时间异常,原因是 <{}>", str, dateFormat, String.valueOf(e));throw new BusinessException(SystemErrorCode.DATE_CONVERT_FAILED);}}/*** 获取当前日期的特定格式** @param timeFormat String 日期格式* @return String* @throws BusinessException 异常*/public static String getCurrentDate(String timeFormat) throws BusinessException {try {DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(timeFormat);return dateTimeFormatter.format(LocalDateTime.now());} catch (Exception e) {LOGGER.error("error message: 获取当前日期的特定格式,数据异常,原因:<{}>", String.valueOf(e));throw new BusinessException((SystemErrorCode.DATE_CONVERT_FAILED));}}/*** 获取当前日期前的若干天的特定格式** @param beforeDays int 天数* @param timeFormat String 日期格式* @return String* @throws BusinessException 异常*/public static String getCurrentDateBeforeSpecialDays(int beforeDays, String timeFormat) throws BusinessException {try {// 获取基于当前日期之前的特定日期LocalDate currentDate = LocalDate.now().minusDays(beforeDays);DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(timeFormat);return dateTimeFormatter.format(currentDate);} catch (Exception e) {LOGGER.error("error message: 获取当前日期前的若干天的特定格式,数据异常,原因:<{}>", String.valueOf(e));throw new BusinessException((SystemErrorCode.DATE_CONVERT_FAILED));}}/*** 依据指标同步频率获取任务开始日期** @param actualIndexFrequency AnalysisEnumEntity.IndexFrequency 指标同步频率* @return String*/public static String getTaskStartDate(AnalysisEnumEntity.IndexFrequency actualIndexFrequency) {String date;switch (actualIndexFrequency) {case INDEX_FREQUENCY_WEEK:date = getCurrentDateBeforeSpecialDays(7,ConstantUtil.DATE_TIME_FORMAT_GENERAL_WITHOUT_HOUR_THREE);break;case INDEX_FREQUENCY_TEN_DAYS:date = getCurrentDateBeforeSpecialDays(10,ConstantUtil.DATE_TIME_FORMAT_GENERAL_WITHOUT_HOUR_THREE);break;case INDEX_FREQUENCY_MONTH:date = getCurrentDateBeforeSpecialDays(30,ConstantUtil.DATE_TIME_FORMAT_GENERAL_WITHOUT_HOUR_THREE);break;case INDEX_FREQUENCY_QUARTER:date = getCurrentDateBeforeSpecialDays(90,ConstantUtil.DATE_TIME_FORMAT_GENERAL_WITHOUT_HOUR_THREE);break;case INDEX_FREQUENCY_HALF_YEAR:date = getCurrentDateBeforeSpecialDays(180,ConstantUtil.DATE_TIME_FORMAT_GENERAL_WITHOUT_HOUR_THREE);break;case INDEX_FREQUENCY_YEAR:date = getCurrentDateBeforeSpecialDays(360,ConstantUtil.DATE_TIME_FORMAT_GENERAL_WITHOUT_HOUR_THREE);break;case INDEX_FREQUENCY_HALF_MONTH:date = getCurrentDateBeforeSpecialDays(15,ConstantUtil.DATE_TIME_FORMAT_GENERAL_WITHOUT_HOUR_THREE);break;// 其它情况默认为每日default:date = getCurrentDate(ConstantUtil.DATE_TIME_FORMAT_GENERAL_WITHOUT_HOUR_THREE);break;}return date;}/*** 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss** @param dateDate Date* @return String*/public static String dateToStrLong(Date dateDate) {SimpleDateFormat formatter = new SimpleDateFormat(ConstantUtil.DATE_TIME_FORMAT_GENERAL_INFO);return formatter.format(dateDate);}/*** 将短时间格式时间转换为字符串 yyyy-MM-dd** @param dateDate Date* @return String*/public static String dateToStr(Date dateDate) {SimpleDateFormat formatter = new SimpleDateFormat(ConstantUtil.DATE_TIME_FORMAT_GENERAL_WITHOUT_HOUR_THREE);return formatter.format(dateDate);}/*** 将短时间格式时间转换为字符串 yyyy-MM-dd 当前时间加1分钟** @param dateDate Date* @return String*/public static String date(Date dateDate) {LocalDateTime now = date2LocalDateTime(dateDate);LocalDateTime localDateTime = now.plusMinutes(1);DateTimeFormatter formatters = DateTimeFormatter.ofPattern(ConstantUtil.DATE_TIME_FORMAT_GENERAL);return formatters.format(localDateTime);}/*** Date 转 LocalDateTime** @param date Date* @return LocalDateTime*/public static LocalDateTime date2LocalDateTime(Date date) {return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();}/*** LocalDateTime 转 Date** @param localDateTime LocalDateTime* @return Date*/public static Date localDateTimeDate(LocalDateTime localDateTime) {return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());}/*** 将短时间格式时间转换为字符串 yyyyMMdd** @param dateDate String* @return String*/public static String dateString(Date dateDate) {SimpleDateFormat formatter = new SimpleDateFormat(ConstantUtil.DATE_TIME_FORMAT_GENERAL_WITHOUT_HOUR_TWO);return formatter.format(dateDate);}/*** 将短时间格式字符串转换为时间 yyyy-MM-dd** @param strDate String* @return Date*/public static Date strToDate(String strDate) {SimpleDateFormat formatter = new SimpleDateFormat(ConstantUtil.DATE_TIME_FORMAT_GENERAL_WITHOUT_HOUR_THREE);ParsePosition pos = new ParsePosition(0);return formatter.parse(strDate, pos);}/*** 将短时间格式字符串转换为时间 yyyyMMdd** @param strDate String* @return Date*/public static Date strDate(String strDate) {SimpleDateFormat formatter = new SimpleDateFormat(ConstantUtil.DATE_TIME_FORMAT_GENERAL_WITHOUT_HOUR_TWO);ParsePosition pos = new ParsePosition(0);return formatter.parse(strDate, pos);}/*** 校验字符串是否为合法的日期格式** @param strDate String* @param format String* @return boolean*/public static boolean isValidDate(String strDate, String format) {try {SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);simpleDateFormat.setLenient(false);return null != simpleDateFormat.parse(strDate);} catch (ParseException e) {LOGGER.error("error message: 校验字符串是否为合法的日期格式,数据异常,原因:", e);return false;}}/*** 判断日期是否有效** @param date String,日期* @param dateFormat String,日期格式* @return boolean True-日期有效 False-日期无效*/public static boolean isDateValid(String date, String dateFormat) {if (StringUtil.isEmpty(date) || StringUtil.isEmpty(dateFormat)) {return false;}try {DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormat.replace("y", "u")).withResolverStyle(ResolverStyle.STRICT);return LocalDate.parse(date, dateTimeFormatter) != null;} catch (Exception e) {LOGGER.error("error message: 日期 <{}> 验证不通过,原因", date, e);return false;}}/*** 获取形如 0819、-08-19、19:19等 形式的当前日期(含时间)** @param dateTimeFormat String,日期格式* @return String 当前日期(含时间),形如 0819、-08-19、19:19等*/public static String getCurrentLocalDateWithSpecialFormat(String dateTimeFormat) {// 线程不安全 'new SimpleDateFormat(dateTimeFormat).format(Calendar.getInstance().getTime())'return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateTimeFormat));}/*** str 类型的日期比较** @param str1 String 日期1* @param str2 String 日期2* @param dateTimeFormat String 日期格式* @return int -2:待对比的数据异常 -1: 日期1 < 日期2; 0: 日期1 = 日期2; 1: 日期1 > 日期2*/public static int dateCompare(String str1, String str2, String dateTimeFormat) {try {if (StringUtil.isEmpty(str1) || StringUtil.isEmpty(str2)) {return -2;}LocalDate date1 = stringToLocalDate(str1, dateTimeFormat);LocalDate date2 = stringToLocalDate(str2, dateTimeFormat);return pareTo(date2);} catch (Exception e) {LOGGER.error("error message: 日期比较异常,原因:<{}>", String.valueOf(e));throw new BusinessException((SystemErrorCode.DATE_CONVERT_FAILED));}}/*** 将 unix 时间戳转换为 相应时区时间** @param instant Instant* @param zoneIdType SystemEnumEntity.ZoneIdType* @param dateFormatter String* @return String*/public static String instantToString(Instant instant,SystemEnumEntity.ZoneIdType zoneIdType,String dateFormatter) {if (null == instant ||null == zoneIdType ||StringUtil.isEmpty(dateFormatter)) {return "";}try {DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormatter).withZone(ZoneId.of(zoneIdType.getLabel()));return dateTimeFormatter.format(instant);} catch (Exception e) {LOGGER.error("error message: 时间转换异常,原因是 ", e);return "";}}/*** 将 String 时间转换为 相应时区下的时间戳** @param dateTimeString* @param zoneIdType SystemEnumEntity.ZoneIdType* @param dateFormatter String* @return Instant*/public static Instant stringToInstant(String dateTime,SystemEnumEntity.ZoneIdType zoneIdType,String dateFormatter) throws BusinessException {if (StringUtil.isEmpty(dateTime) ||null == zoneIdType ||StringUtil.isEmpty(dateFormatter)) {throw new BusinessException(GuiErrorCode.ACCESS_PARAMETER_INVALID);}try {DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormatter);LocalDateTime localDateTime = LocalDateTime.parse(dateTime, dateTimeFormatter);return localDateTime.atZone(ZoneId.of(zoneIdType.getLabel())).toInstant();} catch (Exception e) {LOGGER.error("error message: 字符串格式时间 <{}> 转换为 Instant 异常,原因是", dateTime, e);throw new BusinessException(SystemErrorCode.DATE_CONVERT_FAILED);}}/*** 校验时间间隔** @param startString 时间间隔开始时间* @param end String 时间间隔结束时间* @param dateTimeFormat String 时间格式* @return boolean True-时间间隔无效 False—时间间隔有效*/public static boolean isIntervalInvalid(String start, String end, String dateTimeFormat) {if (StringUtil.isEmpty(start)|| StringUtil.isEmpty(end)|| StringUtil.isEmpty(dateTimeFormat)) {LOGGER.error("error message: 待校验时间间隔参数无效 <start> <{}>, <end> <{}>, <dateTimeFormat> <{}>", start, end, dateTimeFormat);return true;}try {if (!isDateValid(start, dateTimeFormat)|| !isDateValid(end, dateTimeFormat)) {LOGGER.error("error message: 待间间隔开始时间 <start> <{}>, 时间间隔结束时间 <end> <{}> 不是对应的日期格式 <dateTimeFormat> <{}>", start, end, dateTimeFormat);return true;}return dateCompare(start, end, dateTimeFormat) > 0;} catch (Exception e) {LOGGER.error("error message: 待校验校验时间间隔参数异常,原因:", e);return true;}}/*** 将 Date 转为 LocalDate** @param date Date* @return java.time.LocalDate;*/public static LocalDate dateToLocalDate(Date date) {return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();}/*** 将 LocalDateTime 转换为对应的格式的字符串** @param localDateTime LocalDateTime* @param dateTimeFormat String 时间格式* @return String* @throws BusinessException 异常*/public static String localDateTimeToString(LocalDateTime localDateTime, String dateTimeFormat) throws BusinessException {try {if (null == localDateTime|| StringUtil.isEmpty(dateTimeFormat)) {LOGGER.error("error message: 待转换日期 <{}> , 时间格式 <{}> 参数无效", localDateTime, dateTimeFormat);throw new BusinessException((SystemErrorCode.DATE_CONVERT_FAILED));}DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateTimeFormat);return dateTimeFormatter.format(localDateTime);} catch (Exception e) {LOGGER.error("error message: LocalDateTime <{}> 转换为字符串格式 <{}>异常,原因是 <{}>", localDateTime, dateTimeFormat, e);throw new BusinessException((SystemErrorCode.DATE_CONVERT_FAILED));}}/*** 日期范围查询参数校验** @param rangeDateRangeDateVO 日期范围查询VO* @param dateTimeFormat String 时间格式 如 yyyyMMdd* @param bothRequired boolean True- 日期范围开始日期与结束日期都必须指定 False-日期范围开始日期与结束日期二者可选* @return boolean True- 日期范围查询参数无效 False- 日期范围查询参数有效*/public static boolean isRangeDateInvalid(RangeDateVO rangeDate, String dateTimeFormat, boolean bothRequired) {try {if (null == rangeDate|| StringUtil.isEmpty(dateTimeFormat)) {LOGGER.error("error message: 待校验日期范围 <rangeDate> <{}>, <dateTimeFormat> <{} >参数无效", rangeDate, dateTimeFormat);return true;}// 开始日期与结束日期两者都必须指定的场合if (bothRequired) {return isIntervalInvalid(rangeDate.getStartDate(), rangeDate.getEndDate(), dateTimeFormat);}// 开始日期与结束日期两者两者可选else {if (StringUtil.isEmpty(rangeDate.getStartDate())&& StringUtil.isEmpty(rangeDate.getEndDate())) {return true;} else if (!StringUtil.isEmpty(rangeDate.getStartDate())&& StringUtil.isEmpty(rangeDate.getEndDate())) {return !isValidDate(rangeDate.getStartDate(), dateTimeFormat);} else if (StringUtil.isEmpty(rangeDate.getStartDate())&& !StringUtil.isEmpty(rangeDate.getEndDate())) {return !isValidDate(rangeDate.getEndDate(), dateTimeFormat);} else {return isIntervalInvalid(rangeDate.getStartDate(), rangeDate.getEndDate(), dateTimeFormat);}}} catch (Exception e) {LOGGER.error("error message: 待校验期范围异常, 原因是:", e);return true;}}}

主要是针对时间格式,相互转换以及校验的工具类,希望对大家有所帮助!!!

如果觉得《时间工具类 Instant date LocalDate String LocalDateTime 相互转换》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。