1package im.conversations.android.xmpp;
2
3import java.text.ParseException;
4import java.text.SimpleDateFormat;
5import java.util.Date;
6import java.util.Locale;
7
8public final class Timestamps {
9
10 private Timestamps() {
11 throw new IllegalStateException("Do not instantiate me");
12 }
13
14 public static long parse(final String input) throws ParseException {
15 if (input == null) {
16 throw new IllegalArgumentException("timestamp should not be null");
17 }
18 final String timestamp = input.replace("Z", "+0000");
19 final SimpleDateFormat simpleDateFormat =
20 new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
21 final long milliseconds = getMilliseconds(timestamp);
22 final String formatted =
23 timestamp.substring(0, 19) + timestamp.substring(timestamp.length() - 5);
24 final Date date = simpleDateFormat.parse(formatted);
25 if (date == null) {
26 throw new IllegalArgumentException("Date was null");
27 }
28 return date.getTime() + milliseconds;
29 }
30
31 private static long getMilliseconds(final String timestamp) {
32 if (timestamp.length() >= 25 && timestamp.charAt(19) == '.') {
33 final String millis = timestamp.substring(19, timestamp.length() - 5);
34 try {
35 double fractions = Double.parseDouble("0" + millis);
36 return Math.round(1000 * fractions);
37 } catch (final NumberFormatException e) {
38 return 0;
39 }
40 } else {
41 return 0;
42 }
43 }
44}