如何在Java中将时代的秒数转换成小时/分钟/秒? [英] How can I convert seconds since the epoch to hours/minutes/seconds in Java?

查看:1629
本文介绍了如何在Java中将时代的秒数转换成小时/分钟/秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一个快速,低垃圾的方法呢?我不能做简单的模数运算,因为这并不代表闰秒和其他日期/时间有趣的事情。

解决方案

这是一个快速,零垃圾的解决方案。每次调用时都不要创建一个 Calendar 的新实例,因为它是一个非常重的对象,占用了448字节的堆,几乎要微秒进行初始化(Java 6 ,64位HotSpot,OS X)。



HmsCalculator 旨在用于单个线程(每个线程必须使用不同的实例)。

  public class HmsCalculator 
{
private final Calendar c = Calendar.getInstance();

public Hms toHms(long t){return toHms(t,new Hms()); }
public Hms toHms(long t,Hms hms){
c.setTimeInMillis(t * 1000);
return hms.init(c);
}
public static class Hms {
public int h,m,s;
private Hms init(Calendar c){
h = c.get(HOUR_OF_DAY); m = c.get(MINUTE); s = c.get(SECOND);
返回这个;
}
public String toString(){return String.format(%02d:%02d:%02d,h,m,s); }
}

public static void main(String [] args){
System.out.println(new HmsCalculator()。toHms(
System.currentTimeMillis )/ 1000));
}
}

我没有粘贴所有这些静态导入(无聊)。


Is there a fast, low-garbage way to do it? I can't just do simple modulus arithmetic since that doesn't account for leap seconds and other date/time funny business.

解决方案

This is a fast, zero-garbage solution. It is of key importance not to create a new instance of Calendar on each call because it's quite a heavyweight object, taking 448 bytes of heap and almost a microsecond to initialize (Java 6, 64-bit HotSpot, OS X).

HmsCalculator is intended for use from a single thread (each thread must use a different instance).

public class HmsCalculator
{
  private final Calendar c = Calendar.getInstance();

  public Hms toHms(long t) { return toHms(t, new Hms()); }
  public Hms toHms(long t, Hms hms) {
    c.setTimeInMillis(t*1000);
    return hms.init(c);
  }
  public static class Hms {
    public int h, m, s;
    private Hms init(Calendar c) {
      h = c.get(HOUR_OF_DAY); m = c.get(MINUTE); s = c.get(SECOND);
      return this;
    }
    public String toString() { return String.format("%02d:%02d:%02d",h,m,s); }
  }

  public static void main(String[] args) {
    System.out.println(new HmsCalculator().toHms(
       System.currentTimeMillis()/1000));
  }
}

P.S. I didn't paste all those static imports (boring).

这篇关于如何在Java中将时代的秒数转换成小时/分钟/秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆