iOS 按固定格式獲得當前年月日 星期
1、用NSCalendar
獲得如下格式:
-(NSString *)getDateString{
NSDate *date = [NSDatedate];
NSArray * arrWeek=[NSArrayarrayWithObjects:@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六", nil];
NSCalendar *calendar = [NSCalendarcurrentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear
NSInteger year=[components year];
NSInteger month=[components month];
NSInteger day=[components day];
NSInteger week =[components weekday]-1;
NSString * nsDateString= [NSStringstringWithFormat:@"%4ld-%2ld-%ld %@",year,month,day,[arrWeek
//格式在這裡拼裝
return nsDateString;
}
2、用NSDateFormatter
NSDate *date = [NSDatedate];
NSDateFormatter *dateformatter = [[NSDateFormatteralloc]init];
[dateformatter setDateFormat:@"YYYY-MM-dd"];
//[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];設定格式
NSString
[dateformatter setDateFormat:@"HH:mm:ss"];
//[dateformatter setDateFormat:@"HH-mm-ss"]; 設定格式
NSString * timeStr=[dateformatter stringFromDate:date];
NSLog(@"date =%@ ",dateStr);
NSLog(@"time =%@ ",timeStr);
執行結果
date =2016-06-25
time =17:30:32