Created
April 10, 2014 09:59
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that this will divide second timestamps by 1000 if they are after 2038