2012-11-27 85 views

回答

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 
0

此問題的最簡單,最快的方法就是使用它作爲字符串無日期格式:

NSArray* components = [fullDateTime componentsSeparatedByString:@" "]; 
NSString* date = [NSString stringWithFormat:@"%@%@%@", [components objectAtIndex:0], [components objectAtIndex:1], [components objectAtIndex:2]]; 
NSString* time = [components objectAtIndex:3]; 
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); 
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 
-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); 
} 
` 
相關問題