Search code examples
javatimeunit

Extract multiple TimeUnits from a String


I am trying to strip every Time Unit of a String, e.g.

The String "4w10d50m39s" would return a TimeUnit of 4 weeks, a TimeUnit of 10 days, a TimeUnit of 50 minutes, and a TimeUnit of 39 seconds.

How can I achieve this?

Context: I need them to sum all the Time unit converted to millis and use it as a time stamp, it will be used inside a Minecraft server, in a command made to add a rank to a user for an specific amount of time, example: /addrank iLalox Vip 4w5d, that would set the expiration date to: System.currentMillis() + timeInMillis.


Solution

  • To extract unit you can use regex

    \\d+[wdms]
    

    Demo

    Then you can use matcher to extract matches from string and create TimeUnits. There is no Week constant in TimeUnit, so i would present week as amount of weeks * 7 in days.

    public static void main(String[] args) {
        String test = new String("4w10d50m39s");
        Pattern pattern = Pattern.compile("\\d+[wdms]");
        Matcher matcher = pattern.matcher(test);
    
        while(matcher.find()) {
            String unit = matcher.group();
            char timeType = unit.charAt(unit.length() - 1);
            int timeAmount = Integer.parseInt(unit.substring(0, unit.length() - 1));
            if(timeType == 'd') {
                System.out.println(TimeUnit.DAYS.toDays(timeAmount) + " DAYS");
            }
    
            if(timeType == 'm') {
                System.out.println(TimeUnit.MINUTES.toMinutes(timeAmount) + " MINUTES");
            }
    
            if(timeType == 's') {
                System.out.println(TimeUnit.SECONDS.toSeconds(timeAmount) + " SECONDS");
            }
    
            if(timeType == 'w') {
                System.out.println(TimeUnit.DAYS.toDays(timeAmount * 7L) + " DAYS IN WEEK");
            }
        }
    }
    

    Output:

    28 DAYS IN WEEK
    10 DAYS
    50 MINUTES
    39 SECONDS