格式化参数如下:
G: 公元时代,例如AD公元yy: 年的后2位yyyy: 完整年MM: 月,显示为1-12MMM: 月,显示为英文月份简写,如 JanMMMM: 月,显示为英文月份全称,如 Janualydd: 日,2位数表示,如02d: 日,1-2位显示,如 2EEE: 简写星期几,如SunEEEE: 全写星期几,如Sundayaa: 上下午,AM/PMH: 时,24小时制,0-23K:时,12小时制,0-11m: 分,1-2位mm: 分,2位s: 秒,1-2位ss: 秒,2位S: 毫秒
常用日期结构:
yyyy-MM-dd HH:mm:ss.SSSyyyy-MM-dd HH:mm:ssyyyy-MM-ddMM dd yyyy
代码示例:
- (void) loadbaseui{//InstantiationNSDateFormatter *dateformatter = [[NSDateFormatter alloc]init]; [Dateformatter setdateformat:@"Yyyy-mm-dd HH:mm:ss"];//date, string (converted to date in the specified format) NSDate*currentdate = [NSDateDate];NSString*datestring = [Dateformatter stringfromdate:currentdate];NSLog(@"%@", datestring);//string-Date (dateformatter format must be consistent with string format, otherwise null is returned)NSDateFormatter *dateformatter2 = [[NSDateFormatter alloc]init]; [DateFormatter2 setdateformat:@"yyyy mm month DD Day hh"];NSString*string = @"August 28, 2015 13:55";NSDate*target = [DateFormatter2 datefromstring:string];NSLog(@"%@", target);//Output //2015-07-16 14:10:11.771 nsdateformatter[2950:109663] 2015-07-16 14:10:11 //2015-07-16 14:10:11.773 nsdateformatter[2950:109663] 2015-08-28 05:55:00 +0000}
//获取指定时间
-(nsstring *) Gettomorrowday: (nsdate *) adate{//km calendar Nscalendar *gregorian = [[nscalendar alloc] Initwithcalendaridentifier: Nscalendaridentifiergregorian]; Nsdatecomponents *components = [Gregorian components:nscalendarunitweekday | Nscalendarunityear | Nscalendarunitmonth | Nscalendarunitday Fromdate:adate]; [Components Setday: ([Components Day]+1 )]; //get next day date nsdate *beginningofweek = [Gregorian datefromcomponents:components]; NSDateFormatter *dateday = [[NSDateFormatter alloc] init]; [Dateday setdateformat:@ "YYYY-MM-DD" ]; return [Dateday Stringfromdate:beginningofweek];}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
iOS Development-nsdateformatter