java use simpledateformat to parse a input String get ParseException, and just because of a space

huangapple go评论128阅读模式
英文:

java use simpledateformat to parse a input String get ParseException, and just because of a space

问题

输入一个字符串类似于要求的 SimpleDateFormat 格式但会出现 ParseException我进行了几次测试如果我将dd HH之间的空格改为dd-HH”,那么格式变为yyyy-MM-dd-HH:mm:ss”,并且将会成功

第二个测试是我直接写一个字符串如下
`String birthdays = "1998-08-12 12:12:12";`
并对其进行解析同样会成功

所以我的结论是我输入的空格与模式中的空格不同我使用的是 IntelliJ

SimpleDateFormat datef = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Scanner sc = new Scanner(System.in);
System.out.println("请输入您的生日。模式为:" +
"yyyy-MM-dd HH:mm:ss");
String birthday = sc.next();
Date date2 = datef.parse(birthday);
// String birthdays = "1998-08-12 12:12:12";
// Date date2 = datef.parse(birthdays); // 这将会成功
System.out.println(date2);


<details>
<summary>英文:</summary>

I input a string likes the SimpleDateFormat pattern asked, but it will be ParseException. I do several tests. If I change space between &quot;dd HH&quot; to &quot;dd-HH&quot;, the pattern becomes &quot;yyyy-MM-dd-HH:mm:ss&quot;, and it will be successful.
The second test is I write a string directly like 
`String birthdays = &quot;1998-08-12 12:12:12&quot;;`
and parse it, it will also successful.
so my conclusion is the space I input is not the same as the space in the pattern. what I used is IntelliJ.
    SimpleDateFormat datef = new SimpleDateFormat(&quot;yyyy-MM-dd HH:mm:ss&quot;);
    Scanner sc = new Scanner(System.in);
    System.out.println(&quot;Please input your birthday. the pattern is &quot; +
            &quot;yyyy-MM-dd HH:mm:ss&quot;);
    String birthday = sc.next();
    Date date2 = datef.parse(birthday);

// String birthdays = "1998-08-12 12:12:12";
// Date date2 = datef.parse(birthdays); //this will successful
System.out.println(date2);


</details>


# 答案1
**得分**: 1

代替使用 `sc.next()`,请使用 `sc.nextLine()`。

`sc.next()` 会找到第一个空格之前的字符串,但是 `nextLine()` 会接受包括空格在内的整个字符串。

那个问题并不是由于空格引起的。

<details>
<summary>英文:</summary>

Instead of using sc.next() use sc.nextLine()

sc.next() will find the first string till space but nextLine() will accept the entire string including space.

That issue is not because of the space.

</details>



huangapple
  • 本文由 发表于 2020年4月9日 15:53:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/61116364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定