LoginSignup
2
0

More than 5 years have passed since last update.

投稿日時を「X年前,X時間前」とか分かりやすい文字列に変換する

Last updated at Posted at 2018-10-18
func timeAgoString(postTimeInterval:TimeInterval)->String{
  guard timeInterval > 0 else{return ""}

  let now = Date()
  let postTime = Date(timeIntervalSince1970: postTimeInterval)

  let c = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: postTime, to: now)

  if let year = c.year, year > 0 { return "\(year)年前" }
  else if let month = c.month, month > 0{ return "\(month)月前" }
  else if let day = c.day, Int(day/7) > 0{ return "\(Int(day/7))週前" }
  else if let day = c.day, day > 0{ return "\(day)日前" }
  else if let hour = c.hour, hour > 0{ return "\(hour)時間前" }
  else if let minute = c.minute, minute > 0{ return "\(minute)分前" }
  else if let second = c.second, second > 0{ return "\(second)秒前" }
  return "今"
}
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0