如何解析和格式化日期数据?

时间:2013-06-11 20:30:46

标签: ruby date twitter

我编写代码来在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”​​等格式?

1 个答案:

答案 0 :(得分:2)

使用Ruby的标准库Date:

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