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