2012-01-19 26 views
1

我需要比較兩個日期與時間(上午/下午)。我使用了下面的代碼。日期和時間比較包括AM/PM在iphone sdk

-(NSDate*)dateFromString:(NSString*)dateString{ 
    // Convert string to date object 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"yyyy-MM-dd H:mm:ss"]; 
    NSDate *date = [dateFormat dateFromString:dateString]; 
    [dateFormat release]; 

    return date; 
} 

#define kMinute 60 
#define kHour (60*60) 
#define kDay (60*60*24) 
-(NSString*)textFromSeconds:(double)seconds{ 
    if(seconds < kMinute) 
     return [NSString stringWithFormat:@"%0.0f seconds",seconds]; 

    if(seconds < kHour) 
     return [NSString stringWithFormat:@"%0.0f minutes",seconds/kMinute]; 

    if(seconds < kDay) 
     return [NSString stringWithFormat:@"%0.0f hours",seconds/kHour]; 

    return [NSString stringWithFormat:@"%0.0f days", seconds/kDay]; 
} 

-(NSString*)textFromDateString:(NSString*)dateString{ 
    NSDate *date =[self dateFromString:dateString]; 
    double seconds = [[NSDate date] timeIntervalSinceDate:date]; 
    NSString *text = [self textFromSeconds:seconds]; 
    NSLog(@"text is: %@", text); 
    return text; 
} 

-(void)test{ 
    [self textFromDateString:@"2011-02-20 17:19:25"]; 
    [self textFromDateString:@"2011-02-20 17:10:25"]; 
    [self textFromDateString:@"2011-02-20 14:04:25"]; 
    [self textFromDateString:@"2011-02-19 14:04:25"]; 
} 

其工作完美。但我需要將其轉換爲12小時制。所以我需要將兩個日期與AM或PM進行比較。我應該在上面的代碼中做些什麼修改來實現目標?

我將dateformat更改爲@「yyyy-MM-dd HH:mm a」,並使用相同格式的日期進行嘗試,但未能正常工作。

謝謝。

回答

2

嘗試將dateformat更改爲@「yyyy-MM-dd hh:mm a」

+0

那就是cool man .. !!它的工作..謝謝:) – Mithuzz