Java get human understandable time in seconds, minutes, hours & days from milliseconds.


This function returns human readable time from milliseconds. Use this in logging utilities to make sense of time as a common sense. :)

 public static final String getHumanRedableTime(long timeInMs) {
        String r;
        long time = (int) (timeInMs / 1000);
        long secs = time % 60 > 0 ? time % 60 : 0;
        time = time / 60;
        long mins = time % 60 > 0 ? time % 60 : 0;
        time = time / 60;
        long hours = time % 24 > 0 ? time % 24 : 0;
        long days = time / 24;

        r = String.valueOf(secs);
        String s = secs > 1 ? " seconds " : " second ";
        r = r + s;
        if (mins > 0) {
            String m = (mins > 1) ? " minutes " : " minute ";
            r = mins + m + r;
        }
        if (hours > 0) {
            String h = (hours > 1) ? " hours " : " hour ";
            r = hours + h + r;
        }
        if (days > 0) {
            String d = (days > 1) ? " days " : " day ";
            r = days + d + r;
        }
        return r;
    }

Comments

Popular posts from this blog

Delete horizontal, vertical and angled lines from an image using Python to clear noise and read text with minimum errors

Unordered JSON compare for differences using javascript

Java Currency Formatter Changing $ to ¤