开发者

Parsing date like twitter

I've ma开发者_如何学编程de a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What's the best way ? Thanx.


You are looking for Pretty date in JavaScript, by John Resig.

For example:

prettyDate("2008-01-28T20:24:17Z") // => "2 hours ago"
prettyDate("2008-01-27T22:24:17Z") // => "Yesterday"
prettyDate("2008-01-26T22:24:17Z") // => "2 days ago"
prettyDate("2008-01-14T22:24:17Z") // => "2 weeks ago"
prettyDate("2007-12-15T22:24:17Z") // => undefined 


If you are talking in Ruby check that out:

def created_at_pretty 
  _now = Time.now
  dif = (_now - self.created_at).to_i 

  if dif < 60
    dif = "#{dif} seconds"
  elsif dif > 59 && dif < 120 
    dif = "1 minute"
  elsif dif > 119 && dif < 3600
    dif =  "#{dif/60} minutes"
  elsif dif > 3599 && dif < 7200
    dif = "1 hour"
  elsif dif > 7199 && dif < 86400
    dif =  "#{dif/60/60} hours"
  elsif dif > 86399 && dif < 172800
    dif = "1 day"
  elsif dif > 172799 && dif < 5184000
    dif =  "#{dif/60/60/24} days"
  elsif dif > 5183999 && dif < 10368000
    dif = "1 month"
  elsif dif > 10367999 && dif < 62208000
    dif =  "#{dif/60/60/24/30/12} months"
  elsif dif > 62207999 && dif < 124416000
    dif = "1 year"
  elsif dif > 124415999
    dif =  "#{dif/60/60/24/30/12/12} years"
  end  
  "#{dif} ago"

end

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜