考虑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
有哪些方法并找到了
问题
如何从Tue
获取25
和*date
?
答案 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