iOS NSString和NSDate转换
生活随笔
收集整理的這篇文章主要介紹了
iOS NSString和NSDate转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
后臺返回的時間字符串不是標準的時間而是計算機時間的時候,我們需要將它們轉換為標準時間,再進行轉換。
//字符串轉為時間,時間格式自己定? NSString * time = @"1501776000"; ? //時間字符串? NSInteger num = [time integerValue]; ? //轉為int型? NSDateFormatter * formatter = [[NSDateFormatter alloc] init]; ? ? //時間管理 [formatter setDateStyle:NSDateFormatterMediumStyle]; ? ? ?//時間方式 [formatter setTimeStyle:NSDateFormatterShortStyle];? [formatter setDateFormat:@"YYYY-MM-dd"];? NSDate * confromTime = [NSDate dateWithTimeIntervalSince1970:num]; NSString * comfromTimeStr = [formatter stringFromDate:confromTime];? NSLog(@"%@",comfromTimeStr);
時間字符串格式轉換為標準時間
NSString *string = @"20160707094106"; NSDateFormatter *inputFormatter= [[NSDateFormatter alloc] init]; [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; [inputFormatter setDateFormat:@"yyyyMMddHHmmss"]; NSDate *inputDate = [inputFormatter dateFromString:string]; NSLog(@"date= %@", inputDate); NSDateFormatter *outputFormatter= [[NSDateFormatter alloc] init]; [outputFormatter setLocale:[NSLocale currentLocale]]; [outputFormatter setDateFormat:@"yyyy年MM月dd日 HH時mm分ss秒"]; NSString *str= [outputFormatter stringFromDate:inputDate]; NSLog(@"testDate:%@",str);
總結
以上是生活随笔為你收集整理的iOS NSString和NSDate转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算术平方根计算机保留根号,根号计算器
- 下一篇: 关于Xcode隐藏打印的logs的方法