-2

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

4

5 回答 5

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
于 2012-11-27T09:16:17.793 回答
0

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

NSArray* components = [fullDateTime componentsSeparatedByString:@" "];
NSString* date = [NSString stringWithFormat:@"%@%@%@", [components objectAtIndex:0], [components objectAtIndex:1], [components objectAtIndex:2]];
NSString* time =  [components objectAtIndex:3];
于 2012-11-27T09:14:03.323 回答
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);
于 2012-11-27T09:15:11.557 回答
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
于 2012-11-27T09:17:16.603 回答
-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);
}
`
于 2012-11-27T09:21:37.623 回答