LocalDateTime特殊转换
in developCo-De with 0 comment

LocalDateTime特殊转换

in developCo-De with 0 comment

LocalDateTime不带时区,Date带时区

获取时间

//当前时间
LocalDateTime.now();
//当前时间,指定时区
// 本地默认时区时间(时分秒) ---> 偏移位为UTC时间(时分秒)
LocalDateTime.now(ZoneId.of("UTC"))
//当前UTC时间,转换成目标时区时间
LocalDateTime newTime =  
    nowDate  
        .atZone(ZoneId.of("UTC"))  
        .withZoneSameInstant(ZoneId.of("Africa/Lagos"))  
        .toLocalDateTime();

转换Date,Date带时区

// 借助instant
public static Date parseToDate(LocalDateTime localDateTime, TimeZone timeZone) { 
  ZonedDateTime zonedDateTime = localDateTime.atZone(timeZone.toZoneId());  
  return Date.from(zonedDateTime.toInstant());  
}

转换时间戳,时间戳带时区

public static LocalDateTime ofUtc(long timestamp) {  
  Instant instant = Instant.ofEpochMilli(timestamp);  
  return LocalDateTime.ofInstant(instant, CommonConstants.CARD_TRANSACTION_TIME_ZONE);  
}

转换字符串,匹配格式思路


/** 循环格式化匹配 */  
public static final DateTimeFormatter[] dateTimeFormatters = {  
  DateTimeFormatter.ISO_LOCAL_DATE_TIME, DateTimeFormatter.ISO_OFFSET_DATE_TIME, 
};

public static LocalDateTime of(String source, String date, String pattern) {  
  if (StringUtils.isEmpty(date)) {  
    return null;  
  }  
  // 尝试时间戳,UTC
  if (RegularHelper.isNumerical(date)) {  
    return ofUtc(Long.parseLong(date));  
  }  
  // 空时区字串格式,抹掉字串
  if (date.endsWith(".000Z")) {  
    date = date.substring(0, date.length() - 5);  
  }  
  // 小于Local_date_time最小长度,11,尝试LocalDate转换
  if (date.length() < MIN_LOCAL_DATE_TIME_LENGTH) {  
    LocalDate localDate = LocalDate.parse(date);  
    return LocalDateTime.of(localDate, LocalTime.MIN);  
  }  
  // 默认格式  
  DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;  
  // 自定义格式  
  if (StringUtils.hasText(pattern)) {  
    formatter = DateTimeFormatter.ofPattern(pattern);  
  }  
  try {  
    return LocalDateTime.parse(date, formatter);  
  } catch (Exception e) {  
    // 尝试循环匹配  
    for (DateTimeFormatter dateTimeFormatter : dateTimeFormatters) {  
      try {  
        return LocalDateTime.parse(date, dateTimeFormatter);  
      } catch (Exception e1) {  
        // ignore  
      }  
    }  
    // 转换失败,输出日志,抛出异常
    log.error(  
        "LocalDateHelper.parseToLocalDateTime error,source:{}, date:{},pattern:{}",  
        source,  
        date,  
        pattern);  
    // 匹配失败  
    throw e;  
  }  
}
Comments are closed.