简体   繁体   中英

Parsing date times in “X minutes/hours/days/weeks/months/years ago” format

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:

  • 3 days ago
  • 1 minute ago
  • 2 years ago

I don't think is is easily possible with the default Java libraries. Am I right?

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

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM