如何将NSString转换为NSTimeInterval

时间:2013-07-24 14:24:24

标签: iphone objective-c nsstring nsdate nstimeinterval

我的NSString值为“ 22/04/2013 05:56”,根据要求我只想计算这个时间和日期,并显示一些基于条件的消息。

第一个条件: If(字符串日期=当前日期和字符串时间=当前时间)||(字符串日期=当前日期和字符串时间<当前时间1分钟)

第二个条件: If(字符串日期=当前日期和字符串时间>当前时间按分钟数或小时数)

第三个条件:要知道字符串日期是昨天。

第四个条件:要知道字符串日期是前天。

我从服务器收到此字符串。如何使用“22/04/2013 05:56”字符串来实现上述目标。

2 个答案:

答案 0 :(得分:5)

你需要采取两步:

  1. 将字符串转换为NSDate
  2. 将日期转换为timeStamp
  3. 如下所示:

    - (void) dateConverter{
        NSString *string = @"22/04/2013 05:56";
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        // this is imporant - we set our input date format to match our input string
        // if format doesn't match you'll get nil from your string, so be careful
        [dateFormatter setDateFormat:@"dd/MM/yyyy hh:mm"];
        NSDate *date = [[NSDate alloc] init];
        // voila!
        date = [dateFormatter dateFromString:string];
        NSLog(@"dateFromString = %@", date);
    
        //date to timestamp
        NSTimeInterval timeInterval = [date timeIntervalSince1970];
    }
    

    然后实现像以前一样的方法以下方法会有所帮助,虽然它不完全适合你,但我相信你可以修改它来帮助你!

    - (NSString *) timeAgoFor : (NSDate *) date {
        double ti = [date timeIntervalSinceDate:[NSDate date]];
        ti = ti * -1;
    
        if (ti < 86400) {//86400 = seconds in one day
            return[NSString stringWithFormat:@"Today"];
        } else if (ti < 86400 * 2) {
            return[NSString stringWithFormat:@"Yesterday"];
        }else if (ti < 86400 * 7) {
            int diff = round(ti / 60 / 60 / 24);
            return[NSString stringWithFormat:@"%d days ago", diff];
        }else {
            int diff = round(ti / (86400 * 7));
            return[NSString stringWithFormat:@"%d wks ago", diff];
        }
    }
    

答案 1 :(得分:0)

使用dateformatter从字符串转换为date。然后您必须比较日期并获取值

NSString *str=@"22/04/2013 05:56";
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd/MM/YYYY hh:mm"];
NSDate *dateObj= [dateFormatter dateFromString:str];
NSLog(@"%@",dateObj);