我在从String行解析一些信息时遇到了一些问题。在此示例中,我想使用行2011-08-28 19:02:30
。
这个模板我有很多行。如何解析这个日期?感谢
[47.611910999999999, -122.335178] 6 2011-08-28 19:02:30 I'm at Saigon Vietnamese Restaurant II (1529 6th Ave., at Pine St., Seattle) http://example.com
谢谢大家。这是我的解决方案。
private Date parseDate(String line) {
line = line.replaceAll("\\s+", " ").trim();
String[] masWords = line.split(" ");
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = format.parse(masWords[3] + " " + masWords[4]);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
答案 0 :(得分:3)
String[] s1 = "[47.611910999999999, -122.335178] 6 2011-08-28 19:02:30 I'm at Saigon Vietnamese Restaurant II (1529 6th Ave., at Pine St., Seattle) http://t.co/8s86hNX".split(" ");
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for(int i = 1; i< s1.length ; i++ ){
try {
Date date = format.parse(s1[i-1]+" "+s1[i]);
System.out.println("Date found: "+s1[i-1]+" "+s1[i]);
break;
} catch (ParseException e) {
continue;
}
}
如果你知道日期总是在字符串中的同一个地方,你可以通过演员更容易地做到:
String[] s1 = "[47.611910999999999, -122.335178] 6 2011-08-28 19:02:30 I'm at Saigon Vietnamese Restaurant II (1529 6th Ave., at Pine St., Seattle) http://t.co/8s86hNX".split(" ");
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.parse(s1[6]+" "+s1[7]);
答案 1 :(得分:3)
您需要通过删除额外空格来规范化字符串...()正则表达式可以快速轻松地完成,然后拆分字符串,连接构建日期所需的字符串元素,解析那些日期对象Woala ......
这个代码片段:
String chain = "[47.611910999999999, -122.335178] 6 2011-08-28 19:02:30 I'm at Saigon Vietnamese Restaurant II (1529 6th Ave., at Pine St., Seattle) http://t.co/8s86hNX";
chain = chain.replaceAll("\\s+", " ").trim();
System.out.println(chain);
String[] var = chain.split(" ");
for (String string : var) {
System.out.println(string);
}
String string = var[3] + " " + var[4];
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(string);
System.out.println(date);
答案 2 :(得分:2)
String[] parts = str.split(" ");
parts[]
以查找与您的日期和时间相匹配的项目。\d{4}-\d{2}-\d{2}
\d{2}:\d{2}:\d{2}
java.util.Date