How can parse dates that are in the format like X minutes/hours/days/weeks/months/years ago. Here are some examples to show what I\'m referring to:
It actually depends on a context you are referring 'ago', is it from current date, or from specified date.
You can achieve it using Java APIs:
A little snippet based on the Calendar
API.
Pattern p = Pattern.compile("(\\d+)\\s+(.*?)s? ago");
Map<String, Integer> fields = new HashMap<String, Integer>() {{
put("second", Calendar.SECOND);
put("minute", Calendar.MINUTE);
put("hour", Calendar.HOUR);
put("day", Calendar.DATE);
put("week", Calendar.WEEK_OF_YEAR);
put("month", Calendar.MONTH);
put("year", Calendar.YEAR);
}};
String[] tests = {
"3 days ago",
"1 minute ago",
"2 years ago"
};
for (String test : tests) {
Matcher m = p.matcher(test);
if (m.matches()) {
int amount = Integer.parseInt(m.group(1));
String unit = m.group(2);
Calendar cal = Calendar.getInstance();
cal.add(fields.get(unit), -amount);
System.out.printf("%s: %tF, %<tT%n", test, cal);
}
}
Output:
3 days ago: 2012-08-18, 09:21:38
1 minute ago: 2012-08-21, 09:20:38
2 years ago: 2010-08-21, 09:21:38