Search code examples
javadateformatepochseconds

How to convert yyy/MM/ss hh:mm:ss into seconds?


Introduction

I'm trying to get the difference in seconds from two Epochs

i.e

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

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

The diff will be: 5,272,264‬ seconds

This date format comes from a binary file as a String

My code

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

Problem

I have read many questions in how to turn seconds into Epoch, but what about the reverse?

  • Do I have to do it manually?
  • Is there any library I haven't heard of?

So far what I tried only gets the seconds from the Date with SimpleDateFormat but those are not what I expected...

What do I expect from this

I am currently doing homework and I have been task with calculating the price for a parking ticket and I thought, what if the car doesn't leave, let's say... in a week?

If I work only in the format of hh:mm:ss those cars who stay there a whole week will only pay for one day.


Solution

  • ChronoUnit

    I always use ChronoUnit for calculations like this. Works fine.

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

    Output

    86464

    For converting to date with SimpleDateFormat, you can see e.g. Java time since the epoch