iphone - 从字符串中获取 NSDate

标签 iphone ios objective-c xcode

我有一个日期字符串,我正在尝试将其转换为 NSDate 以将其与当前日期时间进行比较。我尝试实现这个,但是得到了我尝试转换的日期的空值。

这是我尝试过的。

-(BOOL)checkTime{

    //create an instance of the database oject
    DataBase * dataBase = [[DataBase alloc] init];

    //get the times
    NSMutableArray *times = [dataBase allDataFrom:@"timings"];

    //set date time to string and refresh time to float.
    NSString *dateStr = times[1];
    float refreshTime = [times[2] floatValue];


    // Convert string to date object
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormat dateFromString:dateStr];

    //get the time now
    NSDate* timeNow = [NSDate date];

    NSLog(@"dateStr: %@",dateStr);
    NSLog(@"DataBase Date: %@",date);
    NSLog(@"Current Date: %@",timeNow);
    NSLog(@"Time until refresh. (seconds): %f", refreshTime);

    // If date is greater than refresh then update the data
    if ([timeNow timeIntervalSinceDate:date] > refreshTime)
    {
        NSLog(@"Data Needs to be checked.");
        return YES;

    }else{
        NSLog(@"Data is fresh.");

        return NO;

    }


}

这就是我从记录我的所有值中得到的结果

dateStr: 2013/02/26  12:39:28
DataBase Date: (null)
Current Date: 2013-02-26 12:57:49 +0000
Time until refresh. (seconds): 30.000000
Data is fresh.

我的语法是否不正确,或者我是否还遗漏了其他内容?

最佳答案

您输入的日期和格式不匹配!

格式:

yyyy-MM-dd HH:mm:ss

输入:

2013/02/26  12:39:28

(斜杠而不是连字符和额外的空格)。

关于iphone - 从字符串中获取 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15091128/

相关文章:

c# - 如何将媒体属性添加到 ASP.NET WebResource.axd Http 处理程序的 CSS LINK html 标记

ios - 每次我尝试登录我的应用程序时 FBSessionStateClosedLoginFailed

ios - 使用 ScrollView 和 ImageView 在 iOS 中构建类似 map 的实现

ios - 按字母顺序对 plist 中的项目进行排序

ios - 在 iOS7.1 UIButton 中设置图像不起作用?

iphone - 哪个是 iOS 中合适的 XML 解析器?

iphone - 将另一个 Nib 加载到 viewController 中

iphone - 如何在不显示对话框的情况下发布到 Facebook?

ios - 如何使用终端在 Objective C 中加密数据并在 Mac 中解密

ios - UITableView 部分周围的边框