English 中文(简体)
Parsing date like twitter
原标题:
  • 时间:2009-11-09 14:21:27
  •  标签:
  • javascript

I ve made 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





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made 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.

热门标签