///根據傳入的時間date,轉換成字串
class func timeDoubleTimeString(date:NSDate)->(String){
let localeDate = NSDate()
///日期轉化成時間
let timeDouble:Double = fabs(localeDate.timeIntervalSinceDate(date))
let time = Int(timeDouble)
if time<60{return "\(time)秒前"}
if time<60*60{return "\(time/60)分鐘前"}
if time<60*60*24{return "\(time/(60*60))小時前"}
///過1天 這裡返回日期,
let dateFormat = NSDateFormatter()
dateFormat.dateFormat = "MM-dd HH:mm"//yyyy-MM-dd HH:mm:ss"
return dateFormat.stringFromDate(date)
}
複製程式碼
/**
- 時間轉換部分
//從1970年開始到現在經過了多少秒 -(NSString *)getTimeSp { NSString *time; NSDate *fromdate=[NSDate date]; time = [NSString stringWithFormat:@"%f",[fromdate timeIntervalSince1970]]; return time; }
//將時間戳轉換成NSDate,轉換的時間我也不知道是哪國時間,應該是格林尼治時間 -(NSDate )changeSpToTime:(NSString)spString { NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[spString intValue]]; NSLog(@"%@",confromTimesp); return confromTimesp; }
//將時間戳轉換成NSDate,加上時區偏移。這個轉換之後是北京時間 -(NSDate*)zoneChange:(NSString*)spString { NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[spString intValue]]; NSTimeZone *zone = [NSTimeZone systemTimeZone]; NSInteger interval = [zone secondsFromGMTForDate:confromTimesp]; NSDate *localeDate = [confromTimesp dateByAddingTimeInterval: interval]; NSLog(@"%@",localeDate); return localeDate; }
//比較給定NSDate與當前時間的時間差,返回相差的秒數 -(long)timeDifference:(NSDate *)date { NSDate *localeDate = [NSDate date]; long difference =fabs([localeDate timeIntervalSinceDate:date]); return difference; }
//將NSDate按yyyy-MM-dd HH:mm:ss格式時間輸出 -(NSString*)nsdateToString:(NSDate *)date { NSDateFormatter dateFormat=[[NSDateFormatter alloc]init]; [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSString string=[dateFormat stringFromDate:date]; NSLog(@"%@",string); return string; }