001/*
002 * JPPF.
003 * Copyright (C) 2005-2018 JPPF Team.
004 * http://www.jppf.org
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.jppf.utils;
020
021import java.util.concurrent.TimeUnit;
022
023/**
024 * Utility methods for date and time manipulation and conversion.
025 * @author Laurent Cohen
026 */
027public final class DateTimeUtils {
028  /**
029   * Convert the specified duration expressed in the specified time unit into milliseconds.
030   * If the unit is smaller than a millisecond (either {@link java.util.concurrent.TimeUnit#NANOSECONDS TimeUnit.NANOSECONDS} or
031   * {@link java.util.concurrent.TimeUnit#MICROSECONDS TimeUnit.MICROSECONDS}), the result will be rounded to the closest millisecond.
032   * @param time the duration to convert.
033   * @param unit the unit in which the duration is expressed.
034   * @return the duration converted to milliseconds.
035   */
036  public static long toMillis(final long time, final TimeUnit unit) {
037    long millis = TimeUnit.MILLISECONDS.equals(unit) ? time : TimeUnit.MILLISECONDS.convert(time, unit);
038    long remainder = 0L;
039    if (TimeUnit.NANOSECONDS.equals(unit)) {
040      remainder = time % 1000000L;
041      if (remainder >= 500000L) millis++;
042    } else if (TimeUnit.MICROSECONDS.equals(unit)) {
043      remainder = time % 1000L;
044      if (remainder >= 500L) millis++;
045    }
046    return millis;
047  }
048
049  /**
050   * Return the time in miliis elapsed since the start given in nanos.
051   * @param startNanos the start value.
052   * @return the elapsed time coverted to millis.
053   */
054  public static long elapsedFrom(final long startNanos) {
055    return (System.nanoTime() - startNanos) / 1_000_000L;
056  }
057}