• java 时间字符串中毫秒值时有时无,怎么解析


    java 时间字符串中毫秒值时有时无,怎么解析

    • 针对某个值 时有时无的情况,可用 [xxx] 括起来,标识
      public void testDate2() {
      
              // 针对某个值 时有时无的情况,可用 [] 括起来,标识
              DateTimeFormatter settleTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]");
              String date = "2021-02-26 07:35:23";
              String date2 = "2021-02-26 07:35:23.121";
      
              TemporalAccessor parse = settleTimeFormatter.parse(date);
              TemporalAccessor parse2 = settleTimeFormatter.parse(date2);
              System.out.println(parse);
              System.out.println(parse2);
      
      
          }
      
    • 针对 某个值位数不一定的时候,用SimpleDateFormat 解析不报错,用DateTimeFormatter 解析报错的处理
      说明:针对某个值的位数不固定的情况,可用用 ParsePosition 规定,从某个索引开始,按索引值与对应的时间值区匹配,而不是字段的长度与匹配格式不匹配就抛出异常
      	public void testDate3() throws ParseException {
      
          
      
          DateTimeFormatter settleTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.S]");
          String date = "2021-02-26 10:50:07";
          String date1 = "2021-02-26 10:50:07.1";
          String date2 = "2021-02-26 10:50:07.17";
          String date3 = "2021-02-26 10:50:07.172";
      
          // 针对某个值的位数不固定的情况,可用用 ParsePosition 规定,从某个索引开始,按索引值与对应的时间值区匹配
          TemporalAccessor parse = settleTimeFormatter.parse(date,new ParsePosition(0));
          TemporalAccessor parse1 = settleTimeFormatter.parse(date1,new ParsePosition(0));
          TemporalAccessor parse2 = settleTimeFormatter.parse(date2,new ParsePosition(0));
          TemporalAccessor parse3 = settleTimeFormatter.parse(date3,new ParsePosition(0));
          System.out.println(parse);
          System.out.println(parse1);
          System.out.println(parse2);
          System.out.println(parse3);
      
      
      }
      
  • 相关阅读:
    hutool 解析 Excel
    上传文件
    Cannot construct instance of `com.**` (although at least one Creator exists)
    Java8之Optional
    java8之Stream
    java8之Lambda
    springboot+mybatis事务管理
    queryWrapper in like
    Java 组装 Tree
    JWT
  • 原文地址:https://www.cnblogs.com/kzcming/p/14636206.html
Copyright © 2020-2023  润新知