java - Parsing date times in "X minutes/hours/days/weeks/months/years ago" format -
how can parse dates in format x minutes/hours/days/weeks/months/years ago. here examples show i'm referring to:
- 3 days ago
- 1 minute ago
- 2 years ago
i don't think is possible default java libraries. right?
a little snippet based on 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" }; (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
Comments
Post a Comment