我必须发送一条包含系统当前时间(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来做到这一点吗?
long current_time = System.currentTimeMillis() * 1000000L;
我将 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;
}
Duration
.between(
Instant.UTC ,
Instant.now()
)
.toNanos()
使用 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() ;