所以我对 Java 中的日历/时间/日期内容有点陌生,但我在网上阅读了很多有关它们的内容。
这是我必须做的:
我有一个外部设备,它将 Avl 数据包发送到我的通信服务器,并且我正在解析数据部分。
在数据包中的某个位置,设备发送一个 32 位的时间戳,我必须将其解析/转换为保存 GPS 点记录的时间。
时间戳给出了从 2007.01.01 00:00 UTC 算起的秒数
现在这是一个示例代码,我认为这是我在其余实验中尝试过的最接近的代码。
DateFormat 格式化程序 = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
long now = (long)(TimeStampSeconds.longValue() * 1000);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(2007, 0, 1);
calendar.setTimeInMillis(now);
System.out.println(now + " = " + formatter.format(calendar.getTime()));
之后我发现 calendar.set 没有创建一个新纪元,因此 .setTimeInMills 不起作用。尽管我得到了一些疯狂的结果,例如:
二进制时间戳是:0000101011000001010110001111011100001111
秒:46193506063
46193506063000 = 25/10/3433 04:27:43.000
难道我不应该错过1970年到2007年这37年吗?
我想找到一种方法,从我从设备获得的秒数中找到时间,但它们的纪元为 1/1/2007,而 java 的纪元为 1/1/1970..
编辑:我想要的是时间:1/1/2007 加上时间戳的时间。希望我能稍微澄清一下这个问题..
有人有什么想法吗? 提前谢谢
最佳答案
看来您想要做的只是将您的 now
值添加到 Calendar
中。这很容易做到:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
long now = (long)(TimeStampSeconds.longValue() * 1000);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(2007, 0, 1);
calendar.setTimeInMillis(calendar.getTimeInMillis() + now);
System.out.println(now + " = " + formatter.format(calendar.getTime()));
编辑
关于您的 now
变量所保存的内容,有些奇怪。根据this time converter,46193506063秒
对应于1464.786468258年
。
关于Java - 根据不同纪元的外部设备的时间戳计算时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12514018/