Mega Code Archive

 
Categories / Android / Date Type
 

Returns a string representation of the given number of nanoseconds

class Main {     /**      * Returns a string representation of the given number of nanoseconds.      */     public static String nsToString(long ns) {         if (ns < 1000L) {             return Long.toString(ns) + "ns";         } else if (ns < 1000000L) {             return Long.toString(ns/1000L) + "us";         } else if (ns < 1000000000L) {             return Long.toString(ns/1000000L) + "ms";         } else if (ns < 60000000000L) {             return String.format("%.2fs", nsToS(ns));         } else {             long duration = ns;             long nanoseconds = duration % 1000;             duration /= 1000;             long microseconds = duration % 1000;             duration /= 1000;             long milliseconds = duration % 1000;             duration /= 1000;             long seconds = duration % 60;             duration /= 60;             long minutes = duration % 60;             duration /= 60;             long hours = duration % 24;             duration /= 24;             long days = duration;                          StringBuilder result = new StringBuilder();             if (days != 0) {                 result.append(days);                 result.append('d');             }             if (result.length() > 1 || hours != 0) {                 result.append(hours);                 result.append('h');             }             if (result.length() > 1 || minutes != 0) {                 result.append(minutes);                 result.append('m');             }             result.append(seconds);             result.append('s');             return result.toString();         }     }          /**      * Converts nanoseconds into (fractional) seconds.      */     public static double nsToS(long ns) {         return ((double) ns)/1000000000.0;     } }