String 类型的时间 转为 ZonedDateTime


  以下介绍几种方法,可能还有好多 或者更好的,不足之处请指出谢谢。

          //string 转为date 然后转为 ZonedDateTime
//        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date now=null;
//        try {
//            now=dateFormat.parse(str);
//        } catch (ParseException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//       // ZonedDateTime zdt=ZonedDateTime.from(now.toInstant());
//        ZoneId systemDefault = ZoneId.systemDefault();
//        ZonedDateTime zdt=ZonedDateTime.ofInstant(now.toInstant(), systemDefault);
//        System.out.println(zdt);
//        System.out.println(str);
            //String 转为LocalDateTime 然后转为ZonedDateTime
//         DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        LocalDateTime parse=LocalDateTime.parse(str,df);
//
//        ZoneId zoneId = ZoneId.of( "Asia/Shanghai" );
////        ZonedDateTime now=ZonedDateTime.now();
//        ZonedDateTime zdt = parse.atZone( zoneId );    
//        System.out.println(parse);
//        System.out.println(zdt);
        /**
         * String
         * DateTimeFormatter后添加withZone这个值,String转换为ZonedDateTime中这个值是必须要的,否则转换为string时会报错
         * 使用DateTimeFormatter中的parse方法解析string为DateTimematter格式
         */
        String str="2020-07-10 08:25:30";
        DateTimeFormatter str1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("Asia/Shanghai"));
        ZonedDateTime zdt = ZonedDateTime.parse(str, str1);
        String date=zdt.toString();//返回String字符串
        System.out.println(zdt);
        System.out.println(date);


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM