iOS应用程序中的日期和时间格式

时间:2015-12-23 05:41:26

标签: ios objective-c nsdate nsdateformatter

我从响应中获得了日期格式

2015-12-23 05:17:04

但是,我想检查日期和时间,

  

日期==今天?   date ==昨天?

     

时间== 1小时   时间== 2小时至9小时

怎么做?

4 个答案:

答案 0 :(得分:2)

要查看日期是今天,昨天,明天等等,您可以使用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];
}

答案 1 :(得分:1)

NSDate *date = [NSDate date];

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

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

NSString *now = [dateFormatter stringFromDate:date];

您可以尝试以上代码

祝福

答案 2 :(得分: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];
}

答案 3 :(得分:1)

1.frist你可以将你的字符串格式化为日期,如下所示:

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

2.然后,您可以使用NSDate

的方法
HttpSession session = request.getSession();
String sessionid = session.getId();