Java 如何将yyy/MM/ss hh:MM:ss转换为秒?

Java 如何将yyy/MM/ss hh:MM:ss转换为秒?,java,date,format,epoch,seconds,Java,Date,Format,Epoch,Seconds,导言 我正试图得到两个时代的秒差 i、 e 2019-05-22 18:28:56->1558542536秒 2019-07-22 19:00:00->1563814800秒 差值为:5272264‬ 秒 此日期格式以字符串形式来自二进制文件 我的代码 public static void main(String[] args) throws ParseException { String regEpoch = ""; long result = 0; //System

导言

我正试图得到两个时代的秒差

i、 e

2019-05-22 18:28:56->1558542536秒

2019-07-22 19:00:00->1563814800秒

差值为:5272264‬ 秒

此日期格式以字符串形式来自二进制文件

我的代码

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);} 
}
问题

我读过很多关于如何把秒变成纪元的问题,但是反过来呢

  • 我必须手动操作吗
  • 有没有我没听说过的图书馆
到目前为止,我用SimpleDateFormat尝试的只得到了从日期算起的秒数,但这不是我所期望的

我希望从中得到什么

我现在正在做作业,我一直在计算停车罚单的价格,我想,如果车不开呢,比方说。。。一周后

如果我只以
hh:mm:ss
的格式工作,那些在那里呆一周的车只需支付一天的费用

ChronoUnit
我总是用它来做这样的计算。很好

package test;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class Test2 {

    public static void main(String[] args) throws ParseException {

        LocalDateTime date1 = LocalDateTime.parse("2019-05-22T18:58:56");
        LocalDateTime date2 = LocalDateTime.parse("2019-05-23T19:00:00"); //LocalDateTime.now();

        long seconds = ChronoUnit.SECONDS.between(date1, date2);

        System.out.println(seconds);
    }

}
输出

86464

对于使用SimpleDataFormat转换为日期,您可以看到,例如,

这应该可以工作

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2019-05-22 18:28:56").getTime();
持续时间
让java.time类计算
持续时间

在调整为标准ISO 8601格式后解析输入

LocalDateTime ldtStart = LocalDateTime.parse( "2019-05-22 18:28:56".replace( " " , "T" ) ) ;
时区 指定时区,以说明夏令时(DST)等异常情况。一天并不总是24小时长

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdtStart = ldtStart.atZone( z ) ;
计算持续时间

Duration d = Duration.between( zdtStart , zdtStop ) ;

long seconds = d.toSeconds() ;  // Or `getSeconds` before Java 9.
至于停车费,你更可能需要几个小时

long hours = d.toHours() ; 

提示:您的格式是
HH
,而不是
HH
。我强烈建议您使用java.time而不是SimpleDateFormat。@JonSkeet我已经读过一些关于它的内容。如果你能在几分钟内给我举个例子(我会忙于你的提示),我会很高兴地告诉你要点。我建议创建一个硬编码字符串,然后尝试解析它。这只需要几行代码,这将更容易帮助您。您可以决定暂时使用
SimpleDataFormat
,或者立即转到java.time。您还需要考虑这些日期/时间值在哪个时区。我建议您不要使用<代码> SimpleDateFormat < /代码>和<代码>日期<代码>。这些类设计得很糟糕,而且早已过时,其中前者尤其令人讨厌。使用
LocalDateTime
和/或
ZonedDateTime
DateTimeFormatter
,所有这些都来自“我喜欢思考未来”一个好的建议是不要针对过于复杂的解决方案,相反,选择简单的解决方案,一旦实现了这一点,然后寻找更高级和/或通用的解决方案。假设驾驶人不必为春季时钟倒转时不存在的小时付费,在查询差异之前,请转换为
ZonedDateTime
。这是什么“T”字?它只是ISO 8601标准中日期和时间之间的分隔符。见最后一个问题。如果我使用.now()我也会得到毫秒。我如何解析它们?我在想办法。存储时间的字符串长度必须正好为80字节。@Rob,因为我回来删除了您在我阅读的网站上发布的最后一个问题。很接近,确实如此,但这是不正确的。这有很大的区别。日期是
“2019-05-22 18:28:56”
,它给出的mili是
1556728136
,也就是
“2019年5月1日星期三18:28:56(pm)”
这些可怕的类在几年前被JSR 310中定义的java.time类取代。建议在2019年使用它们是错误的建议。@Whiteglood仅供参考,DST不是唯一的问题。世界各地的政治家都表现出了重新定义其管辖区时区的倾向。半小时、四分之一小时或其他奇怪的调整。采用DST。乐趣永无止境。