1

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 :)

Egis
  • 879
  • 2
  • 9
  • 13
  • See http://stackoverflow.com/questions/8476147/how-to-convert-formatted-date-yyyy-mm-dd-to-unix-time-in-java?rq=1 – Dror Bereznitsky Mar 10 '13 at 13:36
  • possible duplicate of [How to convert date in format "YYYY-MM-DD hh:mm:ss" to UNIX timestamp](http://stackoverflow.com/questions/6704325/how-to-convert-date-in-format-yyyy-mm-dd-hhmmss-to-unix-timestamp) – JB Nizet Mar 10 '13 at 13:36
  • @JBNizet That's javascript. – Boris the Spider Mar 10 '13 at 13:37
  • Oh, right. Then see one of the other gazillions similar posts: http://stackoverflow.com/questions/8476147/how-to-convert-formatted-date-yyyy-mm-dd-to-unix-time-in-java?rq=1 for example. – JB Nizet Mar 10 '13 at 13:38
  • sorry for asking something similar to many other posts but none of other answers seemed to offer exactly what I needed. Got my solution now. Thanks :) – Egis Mar 10 '13 at 14:32

3 Answers3

3

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.

Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
phisch
  • 4,571
  • 2
  • 34
  • 52
1

First you need to parse your date string to a Date and then get the timestamp from that:

final SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");

final String myDateString = "someDateString";
final Date date = dateFormat.parse(myDateString);

final long timestamp = date.getTime();

Have a look at the SimpleDateFormat javadocs for information on which format string to use.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
0

You need to convert your string into java.util.Date with the assistance of SimpleDateFormat (for examples see - https://stackoverflow.com/search?q=simpledateformat+%5Bjava%5D) and then get the number of milliseconds since January 1, 1970, 00:00:00 GMT.

Date dt = new Date();
long unixTimeStamp = dt.getTime();
Community
  • 1
  • 1
user2148736
  • 1,283
  • 4
  • 24
  • 39