Java Millisecond Format millis2String(long n)

Here you can find the source of millis2String(long n)

Description

Covert milliseconds to a String.

License

Apache License

Declaration

public static String millis2String(long n) 

Method Source Code

//package com.java2s;
/**/*ww  w  . ja  va  2s.  c om*/
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /** Covert milliseconds to a String. */
    public static String millis2String(long n) {
        if (n < 0)
            return "-" + millis2String(-n);
        else if (n < 1000)
            return n + "ms";

        final StringBuilder b = new StringBuilder();
        final int millis = (int) (n % 1000L);
        if (millis != 0)
            b.append(String.format(".%03d", millis));
        if ((n /= 1000) < 60)
            return b.insert(0, n).append("s").toString();

        b.insert(0, String.format(":%02d", (int) (n % 60L)));
        if ((n /= 60) < 60)
            return b.insert(0, n).toString();

        b.insert(0, String.format(":%02d", (int) (n % 60L)));
        if ((n /= 60) < 24)
            return b.insert(0, n).toString();

        b.insert(0, n % 24L);
        final int days = (int) ((n /= 24) % 365L);
        b.insert(0, days == 1 ? " day " : " days ").insert(0, days);
        if ((n /= 365L) > 0)
            b.insert(0, n == 1 ? " year " : " years ").insert(0, n);

        return b.toString();
    }
}

Related

  1. getTimeInMillis(String dateString, String format)
  2. microseconds2milliseconds(double us)
  3. millis2hms(final long t)
  4. millis2samples(long ms, double sampleRate)
  5. millis2seconds(long millis)
  6. millisAsTicks(int ms)
  7. milliseconds2String(long millis)
  8. millisecondsPerTick(final int tps)
  9. milliSecondsSince(long startMillis)