【问题标题】:java.time.format.DateTimeParseException: Text '103545' could not be parsed at index 2java.time.format.DateTimeParseException:无法在索引 2 处解析文本“103545”
【发布时间】:2021-12-23 08:45:10
【问题描述】:

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

java.time.format.DateTimeParseException:无法在索引 2 处解析文本“103545”

代码如下:

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

【问题讨论】:

  • 那么您希望“103545”被解析到什么日期?
  • 那么第 35 个月?一年中的世纪在哪里?您的格式模式与您的输入完全不匹配。
  • 我得到java.time.format.DateTimeParseException: Text '103545' could not be parsed at index 4(不是索引2)。这让我怀疑您没有正确粘贴您正在运行的确切代码?
  • Marina,我很想知道您是否对您的问题有任何进一步的了解,因为坦率地说,它看起来有点有趣。我们还有什么可以说的吗?
  • 感谢您的帮助。我修好了!

标签: java date datetime datetime-format java-time


【解决方案1】:

这里的问题是日期解析器必须以指定格式接收日期(在本例中为“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);

【讨论】:

  • 不,没有人愿意使用SimpleDateFormatDate。这些课程很麻烦,而且已经过时了。毫秒的想法可能是正确的(尽管我持怀疑态度),但如果是的话,请使用 java.time 中的Instant。您可以根据需要转换为其他 java.time 类型。
  • 在更正第一个代码 sn-p 中的引号后,我得到了java.time.format.DateTimeParseException: Text '25Sep2000' could not be parsed at index 2
【解决方案2】:

这与预期的一样(大约)。

您的格式模式字符串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);

这个 sn-p 的输出是:

10:35:45

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多