【发布时间】:2019-05-23 10:55:47
【问题描述】:
简介
我正在尝试从两个 Epoch 中获取秒数差异
即
2019-05-22 18:28:56 -> 1558542536 秒
2019-07-22 19:00:00 -> 1563814800 秒
差异将是:5,272,264 秒
此日期格式来自二进制文件作为字符串
我的代码
public static void main(String[] args) throws ParseException
{
String regEpoch = "";
long result = 0;
//System.out.println((fecha = dateFormat.format(date)));
try(RandomAccessFile raf = new RandomAccessFile("binario2.txt", "rw")){
//user inputs a code (for now, doesn't matter if exists or not)
System.out.print("Input a code to look for: ");
String code = scan.next();
while(!code.matches("\\d+"))
{
System.out.println("[ERROR] Only digits accepted");
System.out.print("Input a code to look for: ");
code = scan.next();
}
//Gets the current date in seconds
long getSecs = (new Date().getTime())/1000;
System.out.println("Current tiem in secs: " + getSecs);
//We are "randomly accessing" a binary file. The is no problem here at all. It just works.
//Sets the pointer where I want it, again... this works fine.
raf.seek(27+(80*Integer.parseInt(code)));
//Read the String date correctly, which is 2019-05-22 18:28:56
System.out.println(raf.readUTF());
/*
//Attempt 2
System.out.println(java.time.Instant.ofEpochSecond(Long.parseLong(raf.readUTF())));
Long millis = new SimpleDateFormat("yyyy/MM/ss hh:mm:ss").parse(raf.readUTF()).getTime();
System.out.println(millis);
*/
//Let's try to convert it into seconds... No we can't due to -> Unparseable date: "2019-05-22 18:28:56"
Date dt = dateFormat.parse(raf.readUTF());
long epoch = dt.getTime();
System.out.println("Result is: " + (int)(epoch*1000));
}catch(IOException e){System.out.println("[ERROR] " + e);}
}
问题
我已经阅读了很多关于如何将秒变为 Epoch 的问题,但是反过来呢?
- 我必须手动完成吗?
- 有没有我没听说过的图书馆?
到目前为止,我尝试使用 SimpleDateFormat 仅从 Date 中获取秒数,但这不是我所期望的...
我对此有何期待
我目前正在做作业,我一直在计算停车罚单的价格,我想,如果车不离开,比如说……一周后怎么办?
如果我只以hh:mm:ss 的格式工作,那些在那里呆了一整周的汽车只会支付一天的费用。
【问题讨论】:
-
提示:你的格式是
HH,而不是hh。我强烈建议您使用 java.time 而不是 SimpleDateFormat。 -
@JonSkeet 我读过一些关于它的文章。如果你能提供几个例子(我会忙于你的提示),我很乐意给你加分。
-
我建议创建一个minimal reproducible example 对字符串进行硬编码,然后尝试解析它。只需要几行代码,这将使您更容易为您提供帮助。您可以决定暂时使用
SimpleDateFormat,或者立即转到 java.time。您还需要考虑这些日期/时间值所在的时区。 -
我建议你不要使用
SimpleDateFormat和Date。这些类设计不佳且早已过时,尤其是前者,尤其是出了名的麻烦。而是使用LocalDateTime和/或ZonedDateTime和DateTimeFormatter,均来自java.time, the modern Java date and time API。 -
"我喜欢展望未来" 一个好的建议是不要针对复杂的解决方案,而是选择简单的解决方案,一旦实现,然后寻找更高级的解决方案和/或通用解决方案。
标签: java date format epoch seconds