2013-06-11 33 views
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 

的日期說成「週二6月11日15點35分31秒+0000 2013」​​。我如何解析日期並將其更改爲諸如「06.11.2013」​​之類的格式?

+1

你可以寫一個小的代碼來說明您的問題...你確定這些鍵是公開的 – sethi

+1

好或不好,他們現在是一個公開記錄的問題,因爲沒有任何東西在Stack Overflow上消失,甚至沒有編輯過的數據。 OP將必須獲得新的密鑰。 –

回答

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 
+0

將輸入此代碼以更改顯示的日期? – cmart

+0

print_timeline循環內部。解析來自tweet ['created_at']的數據並放入格式化的數據。 –

+0

所以這個循環是這樣的: #打印數據約鳴叫 列表DEF print_timeline(微博) #代碼添加到通過每個TWEET迭代並打印其文本 tweets.each做|鳴叫| puts「#{tweet [」user「] [」name「]},#{tweet [」text「]},#{tweet [」created_at「]},#{tweet [」id「]}」 d = DateTime.parse('#{tweet [「created_at」]') puts d.strftime('%m。%d。%y') end end – cmart