如何在Java中使用纳秒纪元时间?

问题描述 投票:0回答:3

我必须发送一条包含系统当前时间(EPOCH)的消息,该消息将根据以下详细信息发送。还以纳秒为单位发送 EPOCH 时间。

field - current_time
type - UINT64
byte size - 8
value - 0 to 1.84467E+19

我的消息结构如下,

class MsgHeader {
   int message_length;
   String sender_sys;
   String destination_sys;
   **int current_time;**
   char message_type;

................

}

有人可以建议我如何使用java来做到这一点吗?

java integer epoch
3个回答
2
投票
long current_time = System.currentTimeMillis() * 1_000_000L;

0
投票

我将 current_time 的长值转换为字节,如下所示。

public static byte[] longToBytes(long current_time) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(Long.SIZE / 8);
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeLong(current_time);
        byte[] result = baos.toByteArray();
        dos.close();
        System.out.println(result.length);//length=8bytes
        return result;
    }

0
投票

tl;博士

Duration               // Represent a span of time unattached to the time line.    
    .between(          // Calculate elapsed time.
        Instant.UTC ,  // Constant for 1970-01-01T00:00Z.
        Instant.now()  // Current moment as seen with an offset from UTC of zero hours-minutes-seconds.
    )                  // Returns a `Duration` object.
    .toNanos()         // Returns a `long` integer.

java.time

使用 JSR 310 中定义的现代 java.time 类。

要获取自 UTC 1970 年第一个时刻 (1970-01-01T00:00Z) 以来的纳秒计数:

Instant now = Instant.now() ;
Duration d = Duration.between( Instant.UTC , now ) ;
long nanos = d.toNanos() ;
© www.soinside.com 2019 - 2024. All rights reserved.