我在解析时差时感到困惑[我从网页收到]。
例如:我得到一个这样的字符串:2 years 10 weeks 3 days 6 hours 7 min ago
。请注意,在统一的情况下,尾随s
,和year
可能不存在,并且不存在于.week
day
hour
min
目前,我想获得这样存储的差异并获得实际的日期和时间[通过从当前时间减去?]。
而且,我很困惑该怎么办?我知道时间解析方法,但它不是常规时间,而且还有尾随s
!
任何人都可以提出一个好的方法吗?
使用@Eluvatar 的建议,假设每个部分之间有一个空格:
Calendar cal = Calendar.getInstance();
String original = "2 years 10 weeks 3 days 6 hours 7 min ago";
// Split on whitespace separators ("\s+" means "one or more whitespace characters"),
// having trimmed whitespace at beginning and end.
String[] split = original.trim().split("\s+");
// Now parse each entry
int num = split.length;
int pos = 0;
while ((num-pos) >= 2) {
if (split[pos].regionMatches(true, 0, "year", 0, 4)) {
cal.add(Calendar.YEAR, -Integer.decode(split[++pos]));
}
else if (split[pos].regionMatches(true, 0, "month", 0, 5)) {
cal.add(Calendar.MONTH, -Integer.decode(split[++pos]));
}
else if (split[pos].regionMatches(true, 0, "week", 0, 4)) {
cal.add(Calendar.WEEK_OF_YEAR, -Integer.decode(split[++pos]));
}
// And so on through the other potential values, note that the last
// number in regionMatches is the number of characters to match.
pos++;
}
"\s+" 可能需要变为 "\s+",请参阅如何使用任何空白字符作为分隔符拆分字符串?.
您可以使用此代码。这考虑了s
s 和可能缺少某些标记。
String orig = "2 years 10 weeks 3 days 6 hours 7 min ago";
String[] split = orig.replaceAll("[^0-9]+", " ").trim().split(" ");
Calendar cal = Calendar.getInstance();
int idx = 0;
if (orig.contains("yea")) cal.add(Calendar.YEAR, -Integer.parseInt(split[idx++]));
if (orig.contains("wee")) cal.add(Calendar.WEEK_OF_MONTH, -Integer.parseInt(split[idx++]));
if (orig.contains("day")) cal.add(Calendar.DATE, -Integer.parseInt(split[idx++]));
if (orig.contains("hour")) cal.add(Calendar.HOUR, -Integer.parseInt(split[idx++]));
if (orig.contains("min")) cal.add(Calendar.MINUTE, -Integer.parseInt(split[idx++]));
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
String formattedString = sdf.format(cal.getTime());
System.out.println(formattedString); // it prints 04-26-2011 02:12:54
我建议计算差异以毫秒为单位的时间,然后从现在减去,这很简单,但是你会遇到闰年的问题。
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -2);
cal.add(Calendar.WEEK_OF_YEAR, -10);
cal.add(Calendar.DAY_OF_YEAR, -3);
cal.add(Calendar.HOUR_OF_DAY, -6);
cal.add(Calendar.MINUTE, -7);
这应该可以正常工作,但我还没有测试过。例如,您还必须处理几周内没有获得价值的情况。