[英]Date and Time Format in iOS application
我從響應中獲取以下日期格式
2015-12-23 05:17:04
但是,我想檢查日期和時間,
日期==今天? 日期==昨天?
時間== 1小時時間== 2小時至9小時
怎么做 ?
要檢查日期是今天,昨天,明天等,您可以使用NSDate-Extensions
例如:
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];
}
NSDate *date = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.dateFormat = [NSString stringWithFormat:@"yyyyMMddHHmmss"]; NSString *now = [dateFormatter stringFromDate:date];
您可以嘗試上面的代碼
最好的祝願
使用此方法可以將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.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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.