Java 时代以来的时间 [英] Java time since the epoch

查看:20
本文介绍了Java 时代以来的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,如何以以下格式打印自纪元以来的时间(以秒和纳秒为单位):

In Java, how can I print out the time since the epoch given in seconds and nanoseconds in the following format :

java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

我的输入是:

long mnSeconds;
long mnNanoseconds;

其中两者的总和是自纪元 1970-01-01 00:00:00.0 以来经过的时间.

Where the total of the two is the elapsed time since the epoch 1970-01-01 00:00:00.0.

推荐答案

你可以这样做

public static String format(long mnSeconds, long mnNanoseconds) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.");
    return sdf.format(new Date(mnSeconds*1000))
           + String.format("%09d", mnNanoseconds);
}

例如

2012-08-08 19:52:21.123456789

<小时>

如果你真的不需要超过毫秒,你可以做


if you don't really need any more than milliseconds you can do

public static String format(long mnSeconds, long mnNanoseconds) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    return sdf.format(new Date(mnSeconds*1000 + mnNanoseconds/1000000));
}

这篇关于Java 时代以来的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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