---
title: "java 时间转换工具"
author: "fftiger"
date: "2015-07-24T00:12:18Z"
tags: []
categories: ["企业架构"]
slug: "java"
draft: false
lastmod: "2015-07-24T00:12:18Z"
id: 2229805
url: "https://fftiger.iteye.com/blog/2229805"
---

发现一个不错的时间工具

java.util.concurrent.TimeUnit

该类是个枚举类，实现了

[Serializable](/java/io/Serializable.html "java.io 中的接口"), [Comparable](/java/lang/Comparable.html "java.lang 中的接口")&lt;[TimeUnit](/java/util/concurrent/TimeUnit.html "java.util.concurrent 中的枚举")&gt;接口。

DAYS，HOURS，MINUTES，SECONDS，MILLISECONDS，MICROSECONDS，NANOSECONDS

分别表示：天、小时、分、秒、毫秒、微妙、纳秒

当然一般用到毫秒就够了。

1、相互转换：

有两种方法，一种是使用toXX(Long duration)

如：TimeUnit.SECONDS.toMillis(1)；

另一种是通过`convert(long sourceDuration,TimeUnit sourceUnit)；`

如：TimeUnit.HOURS.convert(59L, TimeUnit.MINUTES)把分转换成小时。

遗憾的是转换不能进行四舍五入，会造成精度丢失。

2、此类 **sleep**(long timeout)，**timedJoin**([Thread](/java/lang/Thread.html "java.lang 中的类") thread, long timeout)方法

避免了Thread.sleep(long mill)和`Thread.`**join**(long millis)的时间转换。