java TimeUnit gcd

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java TimeUnit gcd相关的知识,希望对你有一定的参考价值。

package com.lchau;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Program {

  public static void main(String[] args) {
    test(72, TimeUnit.HOURS, 3, TimeUnit.DAYS);
    test(73, TimeUnit.HOURS, 73, TimeUnit.HOURS);
    test(60, TimeUnit.MINUTES, 1, TimeUnit.HOURS);
    test(86400, TimeUnit.SECONDS, 1, TimeUnit.DAYS);
    test(86400, TimeUnit.MINUTES, 60, TimeUnit.DAYS);
    test(86401, TimeUnit.MINUTES, 86401, TimeUnit.MINUTES);
    
    // TODO: fix
    test(9600000000L, TimeUnit.HOURS, 4000000000L, TimeUnit.DAYS);
  }

  private static void test(long value, TimeUnit modifier, long expected, TimeUnit unit) {
    TimeUnit factor = gcd(value, modifier);
    boolean test = factor.convert(value, modifier) == expected && factor == unit;
    String format = "%s: %d %s should convert to %d %s";
    System.out.println(String.format(format,
        test,
        value, modifier,
        expected, unit));
  }

  private static TimeUnit gcd(final long value, final TimeUnit base) {
    long nanoseconds = TimeUnit.NANOSECONDS.convert(value, base);
    List<TimeUnit> values = Arrays.asList(TimeUnit.values());
    Collections.reverse(values);

    for (TimeUnit u : values) {
      long gcd = u.convert(nanoseconds, TimeUnit.NANOSECONDS);

      // compensate for loss of precision
      long difference = nanoseconds - u.toNanos(gcd);
      if (difference == 0) {
        return u;
      }
    }
    return base;
  }
}

以上是关于java TimeUnit gcd的主要内容,如果未能解决你的问题,请参考以下文章

Java日期时间API系列5-----Jdk7及以前的日期时间类TimeUnit在并发编程中的应用

coding++:TimeUnit 使用

TimeUnit枚举类

TimeUnit 笔记

TimeUnit的用法

JUC——TimeUnit工具类