Java Time to String timeToString(int time)

Here you can find the source of timeToString(int time)

Description

Helper for CAST({time} AS VARCHAR(n)).

License

Apache License

Declaration

public static String timeToString(int time) 

Method Source Code

//package com.java2s;
/*//from  www  .  java  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 {
    /**
     * The number of milliseconds in a day.
     *
     * <p>This is the modulo 'mask' used when converting
     * TIMESTAMP values to DATE and TIME values.
     */
    private static final long MILLIS_PER_DAY = 86400000L;

    /** Helper for CAST({time} AS VARCHAR(n)). */
    public static String timeToString(int time) {
        final StringBuilder buf = new StringBuilder(8);
        timeToString(buf, time, 0); // set milli second precision to 0
        return buf.toString();
    }

    private static void timeToString(StringBuilder buf, int time, int precision) {
        while (time < 0) {
            time += MILLIS_PER_DAY;
        }
        int h = time / 3600000;
        int time2 = time % 3600000;
        int m = time2 / 60000;
        int time3 = time2 % 60000;
        int s = time3 / 1000;
        int ms = time3 % 1000;
        int2(buf, h);
        buf.append(':');
        int2(buf, m);
        buf.append(':');
        int2(buf, s);
        if (precision > 0) {
            buf.append('.');
            while (precision > 0) {
                buf.append((char) ('0' + (ms / 100)));
                ms = ms % 100;
                ms = ms * 10;

                // keep consistent with Timestamp.toString()
                if (ms == 0) {
                    break;
                }

                --precision;
            }
        }
    }

    private static void int2(StringBuilder buf, int i) {
        buf.append((char) ('0' + (i / 10) % 10));
        buf.append((char) ('0' + i % 10));
    }
}

Related

  1. timeToString(double time, boolean longNames)
  2. timeToString(final Date date)
  3. timeToString(final long time)
  4. timeToString(int s)
  5. timeToString(int time)
  6. timeToString(int time)
  7. TimeToString(int time)
  8. timeToString(java.util.Date date)
  9. timeToString(long time)