2015-12-23 30 views
0

我今天收到下面的日期格式從響應日期和時間格式中的iOS應用

2015-12-23 05:17:04 

但是,我要檢查日期和時間一樣,

日期==? date ==昨天?

時間==1小時 時間== 2小時纔到9小時

怎麼辦呢?

+0

http://stackoverflow.com/questions/2331129/how-to-determine-if-an-nsdate-is-today這可能幫助你 –

+0

http://stackoverflow.com/questions/5388551/how-to-compare-time –

+0

想要在特定日期的兩個日期或小時之間獲得小時的時間? –

回答

1

使用此方法給你的NSString回來。你可以在方法中比較字符串或時間。

-(NSString*)AgoStringFromTime:(NSDate*)dateTime 
{ 
    NSDictionary *timeScale = @{@"sec" :@1, 
           @"min" :@60, 
           @"hr" :@3600, 
           @"day" :@86400, 
           @"week" :@605800, 
           @"month":@2629743, 
           @"year" :@31556926}; 
    NSString *scale; 
    int timeAgo = 0-(int)[dateTime timeIntervalSinceNow]; 

    if (timeAgo < 60) { 
     scale = @"sec"; 
    } else if (timeAgo < 3600) { 
     scale = @"min"; 
    } else if (timeAgo < 86400) { 
     scale = @"hr"; 
    } else if (timeAgo < 605800) { 
     scale = @"day"; 
    } else if (timeAgo < 2629743) { 
     scale = @"week"; 
    } else if (timeAgo < 31556926) { 
     scale = @"month"; 
    } else { 
     scale = @"year"; 
    } 

    timeAgo = timeAgo/[[timeScale objectForKey:scale] integerValue]; 
    NSString *s = @""; 
    if (timeAgo > 1) { 
     s = @"s"; 
    } 

    return [NSString stringWithFormat:@"%d %@%@", timeAgo, scale, s]; 
} 
+1

這個答案是完美的,因爲我想,但它只返回今天,昨天和休息...但我希望像昨天在上午9點50分 –

+1

@佛羅倫斯聽起來不錯。對於昨天你可以把邏輯如果方法返回「日」。你可以使用NSDate + NVTimerAgo庫希望這對你有所幫助。 –

+0

@佛羅倫薩。謝謝。 –

1

NSDate *date = [NSDate date]; 
 

 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
 

 
dateFormatter.dateFormat = [NSString stringWithFormat:@"yyyyMMddHHmmss"]; 
 

 
NSString *now = [dateFormatter stringFromDate:date];

你可以試試上面的代碼

最大的願望

1

1.frist您可以將字符串格式至今,像這樣:

+ (NSDate *)dateFromString:(NSString *)dateString { 
if (!dateString) { 
    return nil; 
} 

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"]; 
[formatter setLocale:[NSLocale currentLocale]]; 
NSDate *date= [formatter dateFromString:dateString]; 

return date; 
} 

2.然後,你可以使用的方法NSDate

+ (instancetype)date;//get current 
- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)refDate;//Returns the interval between the receiver and another given date. 
2

要檢查是否日期是今天,昨天,明天的日期等......你可以使用NSDate-Extensions

ex :

NSDate *date = [self convertStringToDate:@"2015-12-24 12:40:04" formate:@"yyyy-MM-dd HH:mm:ss"]; 
NSLog(@"%d", [date isToday]); 
NSLog(@"%d", [date isTomorrow]); 
NSLog(@"%d", [date isYesterday]); 

- (NSDate *)convertStringToDate: (NSString *)date formate:(NSString *)formate { 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; 
    [dateFormat setDateFormat:formate]; 
    return [dateFormat dateFromString:date]; 
}