IOS开发 -- swift实现的时间戳_控控控-上ke控_新浪博客


static func dateFormatter() -> NSDateFormatter {

let dateFormatter = NSDateFormatter()

dateFormatter.locale = NSLocale(localeIdentifier: "zh_CN")

dateFormatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd HH:mm:ss")


return dateFormatter

}


static func timestampByString(createdTime: String) -> String {

let date = dateFormatter().dateFromString(createdTime)

return timestampByDate(date)

}


static func timestampByDate(createdTime: NSDate?) -> String {

var timestamp = String()

if let date = createdTime {

var distance = NSDate().timeIntervalSinceDate(date)

if distance < 60 * 5 {

timestamp = "刚刚"

}

else if distance < 60 * 60 {

distance = distance / 60

timestamp = "\(Int(distance)) 分钟前"

} else {

let calendar = NSCalendar.currentCalendar()

let unitFlags: NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute]

let nowComp = calendar.components(unitFlags, fromDate: NSDate())

let currentYear = String(nowComp.year)

let currentDay = String(nowComp.day)


let timeComp = calendar.components(unitFlags, fromDate: date)

let year = String(timeComp.year)

var month = String(timeComp.month)

var day = String(timeComp.day)

var hour = String(timeComp.hour)

var minute = String(timeComp.minute)


if timeComp.month < 10 {

month = "0" + month

}

if timeComp.day < 10 {

day = "0" + day

}

if timeComp.hour < 10 {

hour = "0" + hour

}

if timeComp.minute < 10 {

minute = "0" + minute

}

if currentYear == year {

if currentDay == day {

timestamp = "\(hour):\(minute)"

} else {

timestamp = "\(year)-\(month)-\(day) \(hour):\(minute)"

}

} else {

timestamp = "\(year)-\(month)-\(day) \(hour):\(minute)"

}

}

}

return timestamp

 

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值