2012-01-19 29 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