如何从字符串中分别解析日期和时间?

时间:2012-11-27 09:05:17

标签: objective-c

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

5 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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

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);

答案 3 :(得分:0)

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);

输出

Date: 27 Nov 2012
Time: 02:43 PM

答案 4 :(得分:-1)

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);
}
`