Date互转String和时间戳



	//Date转字符串
    private static String convertDateToStr(Date date,String pattrn){
        if(date == null){
            return StringUtils.EMPTY;
        }
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.of("Asia/Shanghai");
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattrn);
        return localDateTime.format(fmt);
    }

	//Date转时间戳
    private static String convertDateToTs(Date date){
        if(date == null){
            return StringUtils.EMPTY;
        }
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.of("Asia/Shanghai");
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        Long milliSecond = localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        return String.valueOf(milliSecond);
    }

	//字符串转Date
    private Date convertStrToDate(String str,String pattrn){
        DateTimeFormatter df = DateTimeFormatter.ofPattern(pattrn);
        LocalDate localDate = LocalDate.parse(str, df);
        if(null == localDate) {
            throw new WechatBusinessException(HttpStatusEnum.BAD_REQUEST.getVal(),"日期格式有误");
        }
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.of("Asia/Shanghai"));
        return Date.from(zonedDateTime.toInstant());
    }

	//时间戳转Date
    private Date convertTsToDate(String ts){
        try {
            Instant timestamp = Instant.ofEpochMilli(Long.valueOf(dateTs));
            ZonedDateTime zonedDateTime = timestamp.atZone(ZoneId.of("Asia/Shanghai"));
            return Date.from(zonedDateTime.toInstant());
        } catch (Exception e) {
            throw new EmrBusinessException(HttpStatusEnum.BAD_REQUEST.getVal(),"日期格式有误");
        }
    }

猜你喜欢

转载自blog.csdn.net/xx897115293/article/details/107980141