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

前端 未结 2 1258
广开言路
广开言路 2021-01-20 20:15

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<
2条回答
  •  心在旅途
    2021-01-20 20:37

    A little snippet based on the Calendar API.

    Pattern p = Pattern.compile("(\\d+)\\s+(.*?)s? ago");
    
    Map fields = new HashMap() {{
        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, %

    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
    

提交回复
热议问题