有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

日期:爪哇。时间总体安排DateTimeParseException:无法在索引2处分析文本“103545”

我试图分析两个不同的日期并计算它们之间的差异,但出现了下一个错误:

java.time.format.DateTimeParseException: Text '103545' could not be parsed at index 2

以下是代码:

    String thisDate= mySession.getVariableField(myVariable).toString().trim();
    
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy");
    LocalDate theDate= LocalDate.parse(thisDate, formatter);

共 (2) 个答案

  1. # 1 楼答案

    这和预期的差不多

    您的格式模式字符串ddMMyyyy指定了两位数的月份天数、两位数的月份和(至少)四位数的年份,总共(至少)八(8)位数。因此,当你给它一个只有6位数字的字符串时,解析必然会失败

    如果您的用户或其他系统被要求以ddMMyyyy格式向您提供日期,而他们向您提供103545,那么他们就是在犯错误。你的验证发现了错误,这是件好事。你可能想给他们一个机会再试一次,给你一个字符串,比如10112021(2021年11月10日)

    如果(只是猜测)103545是指一天中的某个时间,10:35:45,那么需要使用LocalTime类,还需要更改格式模式字符串,以指定小时、分钟和秒,而不是年、月和日期

        String thisDate = "103545";
    
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmmss");
        LocalTime theTime = LocalTime.parse(thisDate, formatter);
        System.out.println(theTime);
    

    此代码段的输出为:

    10:35:45

  2. # 2 楼答案

    这里的问题是,日期分析器必须以指定的格式接收日期(在本例中为“ddMMyyyy”)

    例如,为了让解析器返回有效日期,您需要输入以下内容:

    String thisDate = '25Sep2000';
    
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy");
    LocalDate theDate = LocalDate.parse(thisDate, formatter);
    

    我想你想要的是把一个以毫秒为单位的日期转换成一个特定格式的日期。这就是你能做的:

    
    //Has to be made long because has to fit higher numbers
    long thisDate = 103545;    //Has to be a valid date in milliseconds
      
    DateFormat formatter = new SimpleDateFormat("ddMMyyyy");    //You can find more formatting documentation online
    Date theDate = new Date(thisDate);
    
    String finalDate = formatter.format(theDate);