java - DateTimeFormatter 中的通配符

标签 java parsing java-time

我需要将字符串解析为 LocalDate。该字符串在正则表达式中看起来像 31.* 03 2016(即 .* 表示天数后可能有 0 个或多个未知字符)。

示例输入/输出:31xy 03 2016 ==> 2016-03-31

我希望在 DateTimeFormatter 文档中找到一个通配符语法以允许这样的模式:

LocalDate.parse("31xy 03 2016", DateTimeFormatter.ofPattern("dd[.*] MM yyyy"));

但是我找不到任何东西。

是否有一种简单的方法来使用 DateTimeFormatter 来表达可选的未知字符?

ps:我显然可以在解析之前修改字符串,但这不是我想要的。

最佳答案

java.time 对此没有直接支持。

最接近的是使用 parse(CharSequence,ParsePosition)使用两种不同的格式化程序。

// create the formatter for the first half
DateTimeFormatter a = DateTimeFormatter.ofPattern("dd")

// setup a ParsePosition to keep track of where we are in the parse
ParsePosition pp = new ParsePosition();

// parse the date, which will update the index in the ParsePosition
String str = "31xy 03 2016";
int dom = a.parse(str, pp).get(DAY_OF_MONTH);

// some logic to skip the messy 'xy' part
// logic must update the ParsePosition to the start of the month section
pp.setIndex(???)

// use the parsed day-of-month in the formatter for the month and year
DateTimeFormatter b = DateTimeFormatter.ofPattern("MM yyyy")
    .parseDefaulting(DAY_OF_MONTH, dom);

// parse the date, using the *same* ParsePosition
LocalDate date = b.parse(str, pp).query(LocalDate::from);

虽然以上内容未经测试,但基本上应该可以使用。但是,手动解析它会容易得多。

关于java - DateTimeFormatter 中的通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36063371/

相关文章:

java - 无法在索引 20 处解析文本 '2021-06-22T18:27:03.5577Z'

java - 如何从 BSON 对象中获取可读字符串

java - 获取 javascript 数组中的 bean 数据

java - 用于不同属性的 DynamoDB Mapper 框架

python - 使用 python 从 3d 模型读取数据

php - 从 Bash 脚本修改 PHP 文件

javascript - 使用node.js解析多维人口普查数据

java - 使用 PDFBox 设置字符间距

Java8 解析给定字符串的日期或日期时间格式

java - 比较 java.time.ZonedDateTime 的实例忽略 Java 8 比较中的秒和毫秒瞬间