總結一下關於日期格式的問題彙總。code
//將要轉換的字符串 NSString* string = @"20160512134106"; 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);
G: 公元時代,例如AD公元
yy: 年的後2位 yyyy: 完全年 MM: 月,顯示爲1-12 MMM: 月,顯示爲英文月份簡寫,如 Jan MMMM: 月,顯示爲英文月份全稱,如 Janualy dd: 日,2位數表示,如02 d: 日,1-2位顯示,如 2 EEE: 簡寫星期幾,如Sun EEEE: 全寫星期幾,如Sunday aa: 上下午,AM/PM H: 時,24小時制,0-23 K:時,12小時制,0-11 m: 分,1-2位 mm: 分,2位 s: 秒,1-2位 ss: 秒,2位 S: 毫秒orm
經常使用日期結構: yyyy-MM-dd HH:mm:ss.SSS yyyy-MM-dd HH:mm:ss yyyy-MM-dd MM dd yyyy字符串
//設置延時的時間 meInterval secondsPerDay = 24 * 60 * 60; //設置以時間去建立 NSDate * data = [[NSDate alloc]initWithTimeIntervalSinceNow:-secondsPerDay]; NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init]; [outputFormatter setLocale:[NSLocale currentLocale]]; [outputFormatter setDateFormat:@"yyyy年MM月dd日 HH時mm分ss秒"]; NSString *str = [outputFormatter stringFromDate:data]; NSLog(@"%@",str);