java.text.ParseException: Unparseable date: “1607411173725“ (at offset 13)

https://blog.csdn.net/jjs15259655776/article/details/91451641

SimpleDateFormat.format把date转成String

SimpleDateFormat.parse把String转成date。

tips:

SimpleDateFormat.parse的时候,经常会有ParseException原因是输入的字符串格式跟SimpleDateFormat定义的格式不一致。会报java.text.ParseException: Unparseable date: "1607411173725" (at offset 13)这种类似的错误

 public static void main(String[] args){
        long time = Long.parseLong("1559319223000");
        Date CST = new Date();
        DateFormat cst = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
        try {
//            Date date = new Date(s);
//            System.out.println(date);
//            String format_time = cst.format(date);
            CST = cst.parse(String.valueOf(time));
 
        } catch (ParseException e) {
            System.out.println("error");
        }
 
    }
 

解决方法:

这时候,可以先通过SimpleDateFormat.format把参数转成符合格式的字符串,然后再调用SimpleDateFormat.parse

  Date CST = new Date();
        DateFormat cst = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
        try {
            Date date = new Date(time);
            System.out.println(date);
            String format_time = cst.format(date);
            CST = cst.parse(format_time);
 
        } catch (ParseException e) {
            System.out.println("error");
        }
 
    }

猜你喜欢

转载自blog.csdn.net/z936689039/article/details/110879788
今日推荐