基于JDK1.8进行时间格式化(字符串转ISO-8601标准时间格式)

//(旧)格式化时间,Jdk7:

//将时间字符串转化为标准时间格式
String accessTime = "20181212162923";
if (accessTime != null && accessTime.trim().length() != 0) {
    Date time = new Date();
    //2018-09-09 19:15:14
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
    try {
        time = sdf.parse(accessTime);
    } catch (ParseException e) {

    }
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
    accessTime = sdf2.format(time);
    System.out.println(accessTime);

}
//输出:2018-12-12T16:29:23+08:00

//(新)JDK1.8将字符串转换为标准的ISO-8601的时间格式:

//(新)将字符串转换为标准的ISO-8601的时间格式
        String timestamp = "20181212162923";
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            LocalDateTime dt1 = LocalDateTime.parse(timestamp,formatter);
            ZoneOffset offset = ZoneOffset.of("+08:00");
            OffsetDateTime date = OffsetDateTime.of(dt1,offset);

            DateTimeFormatter formatter2=DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");
            timestamp=date.format(formatter2);
            System.out.println(timestamp);
        }
        catch (DateTimeParseException ex) {
            ex.printStackTrace();
        }
//结果:2018-12-12T16:29:23+08:00


//(新)jdk8 LocalDateTime和字符串互相转换:

//字符串-->>LocalDateTime
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse("2017-07-20 15:27:44", dateTimeFormatter);
        System.out.println("字符串转LocalDateTime: " + localDateTime);
//输出:字符串转LocalDateTime: 2017-07-20T15:27:44


//LocalDateTime-->>字符串
        DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String dateString = dateTimeFormatter2.format(LocalDateTime.now());
        System.out.println("日期转字符串: " + dateString);
//输出:日期转字符串: 2019-07-17 09:35:53

//(新)获取时区:

//获取时区
        System.out.println(LocalDateTime.now(ZoneOffset.systemDefault()).atZone(ZoneOffset.systemDefault()).getOffset());
//输出:+08:00


 

你可能感兴趣的:(基于JDK1.8进行时间格式化(字符串转ISO-8601标准时间格式))