Objective c 如何将日期和时间与字符串分开分析?

Objective c 如何将日期和时间与字符串分开分析?,objective-c,Objective C,我有一个格式为“2012年12月3日1:00PM”的字符串,我需要解析日期和时间,以便在单独的NSStrings中获得“2012年12月3日”和“1:00PM”。我该怎么做?解决此问题最简单(也是最快)的方法是将其用作字符串,而不使用日期格式化程序: NSArray* components = [fullDateTime componentsSeparatedByString:@" "]; NSString* date = [NSString stringWithFormat:@"%@%@%@"

我有一个格式为“2012年12月3日1:00PM”的字符串,我需要解析日期和时间,以便在单独的
NSString
s中获得“2012年12月3日”和“1:00PM”。我该怎么做?

解决此问题最简单(也是最快)的方法是将其用作字符串,而不使用日期格式化程序:

NSArray* components = [fullDateTime componentsSeparatedByString:@" "];
NSString* date = [NSString stringWithFormat:@"%@%@%@", [components objectAtIndex:0], [components objectAtIndex:1], [components objectAtIndex:2]];
NSString* time =  [components objectAtIndex:3];

试试这个……这个可能对你有帮助

NSDateFormatter *formatOld = [[NSDateFormatter alloc] init];
[formatOld setDateFormat:@"dd MMM yyyy hh:mma"]; //3 Dec 2012 1:00PM
NSString *oldDate = @"3 Dec 2012 1:00PM";
NSDate *date = [formatOld dateFromString:oldDate];
NSDateFormatter *newFormate = [[NSDateFormatter alloc]init];
[newFormate setDateFormat:@"dd MMM yyyy 'and' hh:mm a"]; //3 Dec 2012" and "1:00PM
NSString *newdate =[newFormate stringFromDate:date];
NSLog(@"%@",newdate);
输出

日期:2012年11月27日
时间:下午2:43
NSString *strInput = @"3 Dec 2012 1:00PM";
static NSString *format = @"dd MMM yyyy hh:mma";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[dateFormatter setDateFormat:format];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocale];
NSDate *date = [dateFormatter dateFromString:strInput];


static NSString *format1 = @"dd MMM yyyy";
[dateFormatter setDateFormat:format1];
NSString *strDatePart1 = [dateFormatter stringFromDate:date]; // gives 3 Dec 2012
static NSString *format2 = @"hh:mma";
[dateFormatter setDateFormat:format2];
NSString *strDatePart2 = [dateFormatter stringFromDate:date]; // gives 1:00PM
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd MMM YYYY"];
NSDate *date = [NSDate date];
//in your case you have a string in place of date. I have made it generalised. 
//if you have string 

NSString *onlyDate = [dateFormatter stringFromDate:date];
NSLog(@"Date: %@ ", onlyDate);


[dateFormatter setDateFormat:@"hh:mm a"];

NSString *onlyTime=[dateFormatter stringFromDate:date];
NSLog(@"Time: %@ ", onlyTime);
NSString* dateString =  @"3 Dec 2012 1:00PM";
- (int) indexOf:(NSString*)source of:(NSString *)text {
    NSRange range = [source rangeOfString:text];
    if ( range.length > 0 ) {
        return range.location;
    } else {
        return -1;
    }
}

-(void)dostrip{
   NSString* date = [dateString substringToIndex:[self indexOf:@":"]];
   NSLog(@"date: %@", date);
   NSString* hour = [dateString substringFromIndex:[self indexOf:@":"]];
   NSLog(@"hour: %@", hour);
}
`