如何在Java中将日期转换为十六进制

4

我不熟悉Java,需要获取当前日期时间并将其表示为字符串,例如:

#1:135790246811221:1:*,00000000,UP,060B08,0D1908#

其中060B08代表YYMMDD:GPS日期(2006年11月8日)。6个字符,十六进制。

而0D1908代表HHMMSS:发送时间,6个字符,十六进制。

YYMMDD:发送日期(13:25:08),6个字符,十六进制,例如:用060B08表示。

我正在尝试这段代码:

Calendar cal = Calendar.getInstance();
Date date = new Date();
String date_str = String.format("%02x%02x%02x", cal.getTime().getYear(), cal.getTime().getMonth(), cal.getTime().getDay());
String hour_str = String.format("%02x%02x%02x", cal.getTime().getHours(), cal.getTime().getMinutes(), cal.getTime().getSeconds());
String content = "#1:" + imei + ":1:*,00000000,UP,"+ date_str.getBytes() +","+ hour_str.getBytes()+"#";
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
buf.writeBytes(content.getBytes(Charset.defaultCharset()));
channel.write(buf);

但是错误,返回的是:
#1:359672050130411:1:*,00000000,UP,[B@7f07ff6a,[B@d4dd3b6#

只需摆脱 getBytes() 调用。一开始它们为什么存在并不清楚... - Jon Skeet
您想要做的是所谓的序列化。它需要是HEX码吗?在Java中有标准的方法来完成这个操作,例如将其序列化为XML格式。这样你就不必考虑它了。它将是标准的,即使不是Java,您的终点也可以读取它。另外,为了完全序列化一个Calendar对象,您还需要包括它的时区。 - peterh
2个回答

0

0
您可以使用格式化程序对日期进行格式化,然后按如下方式计算十六进制:
public static void main (String[] args) throws Exception
{
    SimpleDateFormat dateF = new SimpleDateFormat("yyMMdd");
    SimpleDateFormat timeF = new SimpleDateFormat("HHmmss");
    Date date = new Date();
    String dateHex = String.format("%020x", new BigInteger(1, dateF.format(date).getBytes("UTF-8")));
    String timeHex = String.format("%020x", new BigInteger(1, timeF.format(date).getBytes("UTF-8")));
    System.out.println("#1:359672050130411:1:*,00000000,UP," + dateHex + "," + timeHex + "#");
}

输出:

#1:359672050130411:1:*,00000000,UP,00000000313630333237,00000000313135363130#

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接