NSDate * senddate=[NSDate date]; NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init]; [dateformatter setDateFormat:@"YYYYMMdd"]; NSString * locationString=[dateformatter stringFromDate:senddate]; NSLog(@"locationString:%@",locationString); [dateformatter release]; //這個有問題,顯示日期不對
關大叔的寫法spa
01 //獲取當前時間 02 NSDate *now = [NSDate date]; 03 NSLog(@」now date is: %@」, now); 04 05 NSCalendar *calendar = [NSCalendar currentCalendar]; 06 NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; 07 NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now]; 08 09 int year = [dateComponent year]; 10 int month = [dateComponent month]; 11 int day = [dateComponent day]; 12 int hour = [dateComponent hour]; 13 int minute = [dateComponent minute]; 14 int second = [dateComponent second]; 15 16 NSLog(@」year is: %d」, year); 17 NSLog(@」month is: %d」, month); 18 NSLog(@」day is: %d」, day); 19 NSLog(@」hour is: %d」, hour); 20 NSLog(@」minute is: %d」, minute); 21 NSLog(@」second is: %d」, second);
獲取星期幾(好用的)能夠獲取:年、月、日、星期幾code
NSDate *datet = [NSDate date];//如今時間 NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"Sunday", @"週一", @"週二", @"週三", @"週四", @"週五", @"週六", nil]; NSCalendar *calendars = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"]; [calendars setTimeZone: timeZone]; NSCalendarUnit calendarUnit = NSCalendarUnitWeekday; NSDateComponents *theComponents = [calendars components:calendarUnit fromDate:datet]; NSInteger unitFlagss = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond; theComponents = [calendars components:unitFlagss fromDate:datet]; int week = [theComponents weekday]; int year=[theComponents year]; int month = [theComponents month]; int day = [theComponents day]; NSLog(@"%d年%d月",year,month); NSLog(@"%d",day); NSLog(@"xingqi%@",[weekdays objectAtIndex:theComponents.weekday]);