gpt4 book ai didi

java - 检查字符串是否只包含日期

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:45:18 27 4
gpt4 key购买 nike

我有一个字符串,可以包含相应格式的日期 (yyyy-MM-dd) 或日期和时间 (yyyy-MM-dd HH:mm:ss)。

我想知道哪些字符串只包含日期。

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dateFormat.parse("2015-02-02"));
System.out.println(dateFormat.parse("2015-02-02 23:23:23"));

在上面的代码中,两个字符串都被成功解析,而只有 first 的格式相同。

最佳答案

我会使用 parse 的重载,它接受一个 ParsePosition - 然后你可以检查位置:

import java.util.*;
import java.text.*;

public class Test {

public static void main(String[] args) throws Exception {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
System.out.println(parseFully(dateFormat, "2015-02-02"));
System.out.println(parseFully(dateFormat, "2015-02-02 23:23:23"));
}

private static Date parseFully(DateFormat format, String text)
throws ParseException {
ParsePosition position = new ParsePosition(0);
Date date = format.parse(text, position);
if (position.getIndex() == text.length()) {
return date;
}
if (date == null) {
throw new ParseException("Date could not be parsed: " + text,
position.getErrorIndex());
}
throw new ParseException("Date was parsed incompletely: " + text,
position.getIndex());
}
}

关于java - 检查字符串是否只包含日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28272843/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com