Objective-C:如何从NSDate获取日期和日期?

时间:2014-09-11 18:24:13

标签: ios objective-c

考虑Convert string to date in my iPhone app

中的示例
NSString *dateStr = @"Tue, 25 May 2010 12:53:58 +0000";

// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EE, d LLLL yyyy HH:mm:ss Z"];
NSDate *date = [dateFormat dateFromString:dateStr]; 
[dateFormat release];

我检查了NSDate有哪些方法并找到了 enter image description here

问题
如何从Tue获取25*date

1 个答案:

答案 0 :(得分:3)

您应该使用NSDateComponents

NSCalendar * calendar = [NSCalendar currentCalendar];
NSDateComponents * dateComponents = [calendar components: NSDayCalendarUnit | NSWeekdayCalendarUnit fromDate: <yourDate>];

NSLog(@"Day in week: %ld", (long)dateComponents.weekday); // Day in week: 3
NSLog(@"Day in month: %ld", (long)dateComponents.day);    // Day in month: 25
NSLog(@"Day name: %@", calendar.shortWeekdaySymbols[dateComponents.weekday - 1]); // Day name: Tue (iOS 8.0 +)

或者在Swift中

let calendar = NSCalendar.currentCalendar()
let dateComponents = calendar.components(.DayCalendarUnit | .WeekdayCalendarUnit, fromDate: <yourDate>)

println("Day in week: \(dateComponents.weekday)") // Day in week: 3
println("Day in month: \(dateComponents.day)")    // Day in month: 25
println("Day name: \(calendar.shortWeekdaySymbols[dateComponents.weekday - 1])") // Day name: Tue