Search code examples
javaparse-platformprettytime

Converting timestamp from parse.com in java


I'm getting my object's createdAt timestamp back from parse.com as 2014-08-01T01:17:56.751Z. I have a class that converts it to relative time.

public static String timeAgo(String time){
  PrettyTime mPtime = new PrettyTime();

  long timeAgo = timeStringtoMilis(time);

  return mPtime.format( new Date( timeAgo ) );
}

public static long timeStringtoMilis(String time) {
  long milis = 0;

  try {
    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date   = sd.parse(time);
    milis       = date.getTime();
  } catch (Exception e) {
    e.printStackTrace();
  }

  return milis;
}

The problem is that this parses the date wrongly. Right now the result says 4 decades ago and this very wrong. What I'm I doing wrong?


Solution

  • Your current date format "yyyy-MM-dd HH:mm:ss" does not work for the given example 2014-08-01T01:17:56.751Z. The format is missing the characters T and Z and the milliseconds. Change it to:

    new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    

    to fix it.

    Also check the examples in the JavaDoc of SimpleDateFormat, because it also shows the correct date format for your example: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.