Java Nano Second Convert appendSecondsToDurationString(final StringBuilder sb, final long seconds, final long nanoseconds)

Here you can find the source of appendSecondsToDurationString(final StringBuilder sb, final long seconds, final long nanoseconds)

Description

append Seconds To Duration String

License

Apache License

Declaration

private static void appendSecondsToDurationString(final StringBuilder sb, final long seconds,
            final long nanoseconds) 

Method Source Code

//package com.java2s;
/*/*ww w  .  j a v  a2s. com*/
 * Copyright 2017 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed 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 {
    private static final long NANOSECONDS_PER_SECOND = 1000000000;

    private static void appendSecondsToDurationString(final StringBuilder sb, final long seconds,
            final long nanoseconds) {
        if (seconds < 0 && nanoseconds > 0) {
            if (seconds == -1) {
                sb.append("0");
            } else {
                sb.append(Math.abs(seconds + 1));
            }
        } else {
            sb.append(Math.abs(seconds));
        }
        if (nanoseconds > 0) {
            final int pos = sb.length();
            if (seconds < 0) {
                sb.append(2 * NANOSECONDS_PER_SECOND - nanoseconds);
            } else {
                sb.append(nanoseconds + NANOSECONDS_PER_SECOND);
            }
            eliminateTrailingZeros(sb);
            sb.setCharAt(pos, '.');
        }
        sb.append('S');
    }

    private static void eliminateTrailingZeros(final StringBuilder sb) {
        while (sb.charAt(sb.length() - 1) == '0') {
            // eliminates trailing zeros in the nanoseconds
            sb.setLength(sb.length() - 1);
        }
    }
}

Related

  1. asNanoSeconds(long seconds)
  2. doubleToNanoseconds(double d)
  3. durationInSeconds(long startNano)
  4. humanReadableNanoseconds(long delta)