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

前端 未结 2 1257
广开言路
广开言路 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:30

    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:

    • tokenize string into three parts using Java Regex API
    • create and manipulate dates using Java Calendar API
    0 讨论(0)
  • 2021-01-20 20:37

    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
    
    0 讨论(0)
提交回复
热议问题