我从网络服务器获取了一些数据。在这个数据中有一个日期(即11-07-1978)。我想将月份作为整数(int month = 7)。
我试图从String中创建一个NSDate,并将月份作为NSDateComponents的组件。但是我只获得了值1。
以下是我的代码片段:
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd";
NSDate *dateFromString = [dateFormatter dateFromString:[[NSUserDefaults standardUserDefaults] objectForKey:@"result_expdate"]];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:dateFromString];
int day = [components day];
int month = [components month];
int year = [components year];
NSLog(@"month = %d", month);
如何将月份作为整数?
答案 0 :(得分:1)
这是一种快速而肮脏的做法 - 这是手工打印的,所以可能有拼写错误...
//chop up the string by "-"
NSString * dateString = @"11-07-2011";
NSArray * tempArray = [dateString componentsSeparatedByString:@"-"];
// set string to month
NSString * monthString = [[tempArray objectAtIndex:1]description];
//remove 0's from date if any
monthString = [monthString stringByReplacingOccurrencesOfString:@"0" withString:@""];
//change string to int
int month = [[NSString stringWithFormat:@"%@",monthString] intValue];