Search code examples
javaunix-timestamp

How to convert “YYYY-MM-DD hh:mm:ss” to UNIX timestamp in Java?


Or, maybe you know a better approach how to solve this problem. I get dates in the format of "YYYY—MM-DD HH:MM:SS" and need to calculate time difference between now then in approximate increments: 1 minute ago, 1 hour ago, etc.

Any pointers much appreciated :)


Solution

  • Have a look at the SimpleDateFormat.

    You can define your pattern and parse it into a Java Date Object:

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = format.parse("your string goes here");
    long timestamp = date.getTime();
    

    The first line defines the SimpleDateFormat (can also be static if you reuse it a lot) The second line parses your input The third line converts it into milliseconds.