当前位置: 代码迷 >> 综合 >> TimeUnit类常用方法
  详细解决方案

TimeUnit类常用方法

热度:62   发布时间:2024-01-26 13:56:41.0
  • TimeUnit 表示给定单元粒度的时间段;
  • 进行时间颗粒度的转换
  • 延时

常用的颗粒度

	/* 天 */TimeUnit.DAYS;/* 小时 */TimeUnit.HOURS;/* 分钟 */TimeUnit.MINUTES;/* 秒 */TimeUnit.SECONDS;/* 毫秒 */TimeUnit.MILLISECONDS;

时间颗粒度转换的方法

	/* 将指定颗粒度的时间转换为纳秒数 */public long toNanos(long tim);/* 将指定颗粒度的时间转换为微秒数 */public long toMicros(long tim);/* 将指定颗粒度的时间转化成毫秒 */public long toMillis(long tim);/* 将指定颗粒度的时间转化成秒 */public long toSeconds(long tim);/* 将指定颗粒度的时间转化成分钟 */public long toMinutes(long tim);/* 将指定颗粒度的时间转化成小时 */public long toHours(long tim);/* 将指定颗粒度的时间转化天 */public long toDays(long tim);/* 将参数颗粒度时间转换为指定颗粒度时间 */public long convert(long sourceDuration, TimeUnit sourceUnit);

例子

	// 5天转换成小时System.out.println(TimeUnit.DAYS.toHours(5));// 1小时转换成分钟System.out.println(TimeUnit.HOURS.toMinutes(1));// 24小时转换成天System.out.println(TimeUnit.HOURS.toDays(24));// 5天转换成小时System.out.println(TimeUnit.HOURS.convert(5,TimeUnit.DAYS));

对于延时的使用

		//延时的用法new Thread(new Runnable() {@Overridepublic void run() {try {System.out.println("开始延时");// 调用sleep方法TimeUnit.HOURS.timedJoin();TimeUnit.SECONDS.sleep(5);System.out.println("延时结束");} catch (InterruptedException e) {e.printStackTrace();}}}).start();

 

  相关解决方案