I am displaying Facebook posts in my Android application using the Facebook SDK. I have the created_time for each post in the format:
2012-01-04T12:28:52+0000
I was able to parse this into a Java Date object like so:
public static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss+SSSS";
public static Date parseDate(String str) {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
try {
Date date = sdf.parse(str);
} catch(ParseException e) {
Log.w(TAG, "Unable to parse date string \"" + str + "\"");
}
return date;
}
Then, I am attempting to display a message describing the time that has elapsed since the post was created using this method:
public static String timeAgoInWords(Date from) {
Date now = new Date();
long difference = now.getTime() - from.getTime();
long distanceInMin = difference / 60000;
if ( 0 <= distanceInMin && distanceInMin <= 1 ) {
return "Less than 1 minute ago";
} else if ( 1 <= distanceInMin && distanceInMin <= 45 ) {
return distanceInMin + " minutes ago";
} else if ( 45 <= distanceInMin && distanceInMin <= 89 ) {
return "About 1 hour";
} else if ( 90 <= distanceInMin && distanceInMin <= 1439 ) {
return "About " + (distanceInMin / 60) + " hours ago";
} else if ( 1440 <= distanceInMin && distanceInMin <= 2529 ) {
return "1 day";
} else if ( 2530 <= distanceInMin && distanceInMin <= 43199 ) {
return (distanceInMin / 1440) + "days ago";
} else if ( 43200 <= distanceInMin && distanceInMin <= 86399 ) {
return "About 1 month ago";
} else if ( 86400 <= distanceInMin && distanceInMin <= 525599 ) {
return "About " + (distanceInMin / 43200) + " months ago";
} else {
long distanceInYears = distanceInMin / 525600;
return "About " + distanceInYears + " years ago";
}
}
The problem is that the create_time of the post is 6 hours ahead of my time (EST). So the timeAgoInWords method doesn’t work correctly. Does Facebook always record the creation time of posts in UTC/GMT +1 hour?
What can I do to convert the creation time so that timeAgoInWords will work correctly for the current user’s timezone, no matter where they are?
This is the code I use to convert a UTC time string to a localized time string. Note the key for conversion is to use the
TimeZonemethodsgetRawOffset(),inDaylightTime(...)andgetDSTSavings().Note my date format is slightly different to what you are using so you’ll need to change it.
Obviously you want a
Dateobject so you just need to change this line……to…
…then you just need to change the return type of the method and return
localDate.