1

我编写了代码来显示来自 Twitter 上公共帐户的推文:

require 'rubygems'
require 'oauth'
require 'json'

# Now you will fetch /1.1/statuses/user_timeline.json,
# returns a list of public Tweets from the specified
# account.
baseurl = "https://api.twitter.com"
path    = "/1.1/statuses/user_timeline.json"
query   = URI.encode_www_form(
    "screen_name" => "CVecchioFX",
    "count" => 10,
)
address = URI("#{baseurl}#{path}?#{query}")
request = Net::HTTP::Get.new address.request_uri

# Print data about a list of Tweets
def print_timeline(tweets)
  # ADD CODE TO ITERATE THROUGH EACH TWEET AND PRINT ITS TEXT
  tweets.each do |tweet|
    puts "#{tweet["user"]["name"]} , #{tweet["text"]} , #{tweet["created_at"]} , #    {tweet["id"]}"
  end
end

# Set up HTTP.
http             = Net::HTTP.new address.host, address.port
http.use_ssl     = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER

# If you entered your credentials in the first
# exercise, no need to enter them again here. The
# ||= operator will only assign these values if
# they are not already set.
consumer_key = OAuth::Consumer.new(
    )
access_token = OAuth::Token.new(
    )

# Issue the request.
request.oauth! http, consumer_key, access_token
http.start
response = http.request request

# Parse and print the Tweet if the response code was 200
tweets = nil
if response.code == '200' then
  tweets = JSON.parse(response.body)
  print_timeline(tweets)
end
nil

日期为“Tue Jun 11 15:35:31 +0000 2013”​​。我该怎么做才能解析日期并将其更改为“06.11.2013”​​等格式?

4

1 回答 1

2

使用 Ruby 的标准库日期:

require 'date'

d = DateTime.parse('Tue Jun 11 15:35:31 +0000 2013')
puts d.strftime('%m.%d.%y')

在您的代码中,只需更新 print_timeline 方法:

def print_timeline(tweets)
  tweets.each do |tweet|
    d = DateTime.new(tweet['created_at'])
    puts "#{tweet['user']['name']} , #{tweet['text']} , #{d.strftime('%m.%d.%y')} , #{tweet['id']}"
  end
end
于 2013-06-11T20:42:21.893 回答