Search code examples
filtertwitter4j

How to obtain a specific person's tweets in a specific time interval (Twitter4J)?


I want to collect some specific people's tweets in recent one year. I'm using Twitter4J, like this:

Paging paging = new Paging(i, 200);
    try {
        statuses = twitter.getUserTimeline("martinsuchan",paging);
    } catch (TwitterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

But how can I filter the Tweets of that user for a certain time interval?

Any answer appreciated


Solution

  • You can filter the statuses locally, based on status.getCreatedAt(). Example:

    try {
        int statusesPerPage = 200;
        int page = 1;
        String username = "username";
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.YEAR, -1);
    
        Twitter twitter = new TwitterFactory().getInstance();
        Paging paging = new Paging(page, statusesPerPage);
        List<Status> statuses = twitter.getUserTimeline(username, paging);
    
        page_loop:
        while (statuses.size() > 0) {
            System.out.println("Showing @" + username + "'s home timeline, page " + page);
            for (Status status : statuses) {
                if (status.getCreatedAt().before(cal.getTime())) {
                    break page_loop;
                }
                System.out.println(status.getCreatedAt() + " - " + status.getText());
            }
            paging = new Paging(++page, statusesPerPage);
            statuses = twitter.getUserTimeline(username, paging);
        }
    } catch (TwitterException te) {
        te.printStackTrace();
    }