-1

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.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
Jonalcaide
  • 560
  • 8
  • 21
  • Hint: your format is `HH`, not `hh`. I would strongly advise you to use java.time rather than SimpleDateFormat though. – Jon Skeet May 23 '19 at 10:56
  • @JonSkeet I've read a bit about it. If you could provide me an example in a few (I will be busy with your Hint) I will gladly give you the points. – Jonalcaide May 23 '19 at 11:00
  • Based on your homework assignment i think you should rather use Period or Duration data types https://docs.oracle.com/javase/tutorial/datetime/iso/period.html – Rob May 23 '19 at 11:02
  • @JonSkeet I either get NumberFormatException or can't be formatted For input string: "2019-05-22 18:28:56". Using your hint – Jonalcaide May 23 '19 at 11:02
  • 1
    I'd suggest creating a [mcve] that hard-codes the string and just tries to parse it then. That only needs to be a few lines of code, which will make it easier to help you. You could decide to stick with `SimpleDateFormat` for the moment, or move to java.time immediately. You also need to consider which time zone these date/time values are in. – Jon Skeet May 23 '19 at 11:04
  • Note that at the moment you're calling `raf.readUTF()` *lots* of times. I'd *at least* store the result in a variable, so you can print it and then parse the same thing, rather than printing one thing then parsing another. – Jon Skeet May 23 '19 at 11:05
  • Is the parking cost really per second, maybe you are over-complicating things... – Joakim Danielson May 23 '19 at 11:06
  • Did you check this? https://stackoverflow.com/questions/8262333/convert-epoch-seconds-to-date-and-time-format-in-java – Hasitha Jayawardana May 23 '19 at 11:11
  • @JoakimDanielson I like to think into the future. More than just plain homework I try to learn and hypothesise "What If this var reaches certain number and the like" – Jonalcaide May 23 '19 at 11:37
  • @HasithaMJayawardana I am trying to do the opposite. Thanks – Jonalcaide May 23 '19 at 11:38
  • 1
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDateTime` and/or `ZonedDateTime` and `DateTimeFormatter`, all from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. May 23 '19 at 11:39
  • 2
    " I like to think into the future" A good advice is not to aim for a solution that is to complicated, instead go for the easy solution and once that has been achieved then look for a more advanced and/or general solution. – Joakim Danielson May 23 '19 at 11:44
  • @JoakimDanielson Generally wise words. In this particular case I should say that parsing date *and* time is not more advanced than parsing time alone. – Ole V.V. May 23 '19 at 11:46

3 Answers3

5

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

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
heiwil
  • 612
  • 4
  • 8
  • Assuming that the motorist shouldn’t pay for the non-existing hour when the clocks are turned forward in the spring, convert to `ZonedDateTime` before querying the difference. – Ole V.V. May 23 '19 at 11:35
  • 1
    What's that 'T' thing? – Jonalcaide May 23 '19 at 11:40
  • 2
    It's just a delimiter between date and time in ISO 8601 standard. See [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations) – heiwil May 23 '19 at 11:58
  • Last question. If I use the .now() I also get miliseconds. How I parse them out? I'm trying to figure it out. The string stored with the time must be exactly 80bytes long. – Jonalcaide May 23 '19 at 12:06
  • @Rob As I was back to remove that last question you posted the website I was reading from. Close call. – Jonalcaide May 23 '19 at 12:10
  • Use `date1.truncatedTo(ChronoUnit.SECONDS)` to get rid of millis (and smaller). – Ole V.V. May 23 '19 at 12:49
2

Duration

Let java.time classes calculate a Duration.

Parse your input after adjusting to standard ISO 8601 format.

LocalDateTime ldtStart = LocalDateTime.parse( "2019-05-22 18:28:56".replace( " " , "T" ) ) ;

Time zone

Specify the time zone, to account for anomalies such as Daylight Saving a Time (DST). Days are not always 24 hours long.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdtStart = ldtStart.atZone( z ) ;

Calculate a duration.

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

long seconds = d.toSeconds() ;  // Or `getSeconds` before Java 9.

For parking charges, you more likely want hours.

long hours = d.toHours() ; 
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • @WhiteGlove FYI, DST is not the only issue. Politicians around the world have shown a penchant for redefining the time zone(s) of their jurisdiction. Half-an-hour, quarter hour, or other odd adjustments. Adopting DST, [dropping DST](https://www.timeanddate.com/news/time/europe-may-scrap-dst.html), [on DST “permanently”](https://en.wikipedia.org/wiki/Time_in_Turkey), [back off DST “permanently”](https://en.wikipedia.org/wiki/Time_in_Russia#Daylight_saving_time). The fun never ends. – Basil Bourque May 23 '19 at 17:19
1

This should work

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2019-05-22 18:28:56").getTime();
  • It does, but it is not correct. It has a huge difference. The date is `"2019-05-22 18:28:56"` and the milis it gives are `1556728136` which is `"Wednesday May 01, 2019 18:28:56 (pm)"` – Jonalcaide May 23 '19 at 11:55
  • 1
    These terrible classes were supplanted years ago by the *java.time* classes defined in JSR 310. Suggesting their use in 2019 is poor advice. – Basil Bourque May 23 '19 at 12:45