[英]Trying to convert a string number “7” to a 07:00 format with SimpleDateFormat
I've got the next java code: 我有下一个Java代码:
SimpleDateFormat formatter = new SimpleDateFormat("kk:mm");
Date rangoInicio = formatter.parse(filtroHorariosIda.get(0));
The value for filtroHorariosIda.get(0) is "7" (quotes includes because it's a string) filtroHorariosIda.get(0)的值为“ 7”(包括引号是因为它是一个字符串)
The problem is java throws the exception 问题是java抛出异常
java.text.ParseException Unparseable date: "7"
I've been reading the java docs and I think it's a perfectly parsing operation. 我一直在阅读Java文档,并且我认为这是一个完美的解析操作。 Where's the problem? 哪里出问题了?
Thanks. 谢谢。
I don't quite understand... kk:mm expects something in the format, well kk:mm. 我不太明白... kk:mm期望格式为kk:mm。 You're giving it "7". 您给它“ 7”。 Shouldn't you pass "7:21" instead (or "7:00" in this case)? 您是否应该通过“ 7:21”(或本例中的“ 7:00”)?
your parse string expects an input containing ":" among other things - your input doesn't contain a ":" so of course SimpleDateFormat won't be able to interpret your input. 您的解析字符串期望输入中包含“:”等-输入不包含“:”,因此SimpleDateFormat当然将无法解释您的输入。
If your input was "7:0" it would work fine. 如果您输入的是“ 7:0”,它将正常工作。
That's because you're trying to parse "7" and saying that it should use "kk:mm" format. 那是因为您试图解析“ 7”并说它应该使用“ kk:mm”格式。
Try this instead 试试这个
Date rangoInicio = formatter.parse(filtroHorariosIda.get(0) + ":00");
For the sake of completeness, a simple test yields the following results: 为了完整起见,一个简单的测试会产生以下结果:
public void testDateParse()
{
String probes[] = {"7","07:00","7:00","7:0",":"};
for (String probe : probes) {
try
{
SimpleDateFormat formatter = new SimpleDateFormat("kk:mm");
Date rangoInicio = formatter.parse(probe);
System.out.println(probe + " is parsable");
}
catch(ParseException ex)
{
System.out.println(probe + " is not parsable");
}
}
}
7 is not parsable 7不可解析
07:00 is parsable 07:00是可解析的
7:00 is parsable 7:00可解析
7:0 is parsable 7:0是可解析的
: is not parsable :不可解析
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.