import java.net.URL; import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.ByteArrayOutputStream; import org.json.JSONArray; import org.json.JSONObject;
String username = "google"; // update // get tweets as JSON URL url = new URL("https://twitter.com/statuses/user_timeline/" + username + ".json"); ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream(); IOUtils.copy(url.openStream(), urlOutputStream); String urlContents = urlOutputStream.toString(); // parse JSON JSONArray jsonArray = new JSONArray(urlContents); // use for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); System.out.println(jsonObject.getString("id")); System.out.println(jsonObject.getString("text")); System.out.println(jsonObject.getString("created_at")); }
Example: from “Wed Feb 17 20:30:11 +0000 2010” to “yesterday”
import java.text.SimpleDateFormat; import java.util.Date;
public static String twitterHumanFriendlyDate(String dateStr) { // parse Twitter date SimpleDateFormat dateFormat = new SimpleDateFormat( "EEE MMM dd HH:mm:ss ZZZZZ yyyy", Locale.ENGLISH); dateFormat.setLenient(false); Date created = null; try { created = dateFormat.parse(dateStr); } catch (Exception e) { return null; } // today Date today = new Date(); // how much time since (ms) Long duration = today.getTime() - created.getTime(); int second = 1000; int minute = second * 60; int hour = minute * 60; int day = hour * 24; if (duration < second * 7) { return "right now"; } if (duration < minute) { int n = (int) Math.floor(duration / second); return n + " seconds ago"; } if (duration < minute * 2) { return "about 1 minute ago"; } if (duration < hour) { int n = (int) Math.floor(duration / minute); return n + " minutes ago"; } if (duration < hour * 2) { return "about 1 hour ago"; } if (duration < day) { int n = (int) Math.floor(duration / hour); return n + " hours ago"; } if (duration > day && duration < day * 2) { return "yesterday"; } if (duration < day * 365) { int n = (int) Math.floor(duration / day); return n + " days ago"; } else { return "over a year ago"; } }
Note: logic from the the Twitter Profile Widget Javascript file.
For a more advanced use (updating status, search, etc), use Twitter4J