Skip to content

Instantly share code, notes, and snippets.

@feldoh
Created April 10, 2014 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feldoh/10363722 to your computer and use it in GitHub Desktop.
Save feldoh/10363722 to your computer and use it in GitHub Desktop.
Simple Java function to parse timestamps in many different sources to a valid Java long timestamp in milliseconds.
public static long parseTimestamp(String strTimestamp){
/** Parsing inconsistent timestamps:
* 1 - Sometime they are longs e.g. 230923409234 (Timestamp in milliseconds)
* 2 - Another format is double e.g. 234234234.234 (Timestamp in milliseconds / 1000)
* 3 - Even integers on occasion e.g. 234234234 (Timestamp in seconds)
* 4 - Also e-notation e.g. 1.382298592059E9 (Timestamp in milliseconds / 1000)
* 5 - And e-notation for doubles e.g. 1.380604046071e+12 (Timestamp in milliseconds)
*
* All timestamps in seconds are less than the maximum value of an Integer (2147483647).
* All timestamps in milliseconds are greater than the maximum value of an Integer (2147483647).
* Thus if it is less than this value multiply by 1000.
*
* Whichever format it is, this code will convert it to a timestamp in milliseconds.
*/
Long timestamp;
double dblTimestamp = Double.parseDouble(strTimestamp);
timestamp = Math.round(dblTimestamp * (dblTimestamp < Integer.MAX_VALUE ? 1000 : 1));
return timestamp;
}
@feldoh
Copy link
Author

feldoh commented Oct 30, 2014

Note that this will divide second timestamps by 1000 if they are after 2038

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment