NSDate混淆dateFromString格式

时间:2013-05-16 10:27:14

标签: ios nsdate nsdateformatter

//Grab current day from sys date all I am interested in is the day i.e 01 - 31 days of month
NSDateFormatter *dayFormatter = [[NSDateFormatter alloc] init];
[dayFormatter setDateFormat:@"dd"];
NSString *dayString = [dayFormatter stringFromDate:[NSDate date]];

稍后在我的代码中,我想将此字符串dayString转换为NSDate,如下所示但是dayFromString然而格式不仅仅是日期是2000-01-16 00:00:00 +0000所有我想要的是16

NSDate *dayFromString = [dayFormatter dateFromString:dayString];
NSLog(@"Day from string %@", dayFromString);

编辑:

也许这解释了为什么我需要dayFromString的NSDate对象

//sepDates is a JSON array with comma separated dates i.e 13, 27, 29 of which I split it indexes so 13 is at index 0 27 at 1 and 29 at 2. May string is the string that holds the above dates
        sepDates = [mayString componentsSeparatedByString:@","];

//Day string is todays date i.e 16 (16th)
        NSDate *dayFromString = [dayFormatter dateFromString:dayString];
        NSLog(@"Day from string %@", dayFromString);

        double min = [dayFromString timeIntervalSinceDate:[sepDates objectAtIndex:0]];
        NSLog(@"Min %f", min);

//I then want to calculate which of the dates in the sepDates array at index is closest to todays current day 16

        int minIndex = 0;
        for (int d = 1; d < [sepDates count]; ++d)
        {
            double currentmin = [dayFromString timeIntervalSinceDate:[sepDates objectAtIndex:d]];
            if (currentmin < min) {
                min = currentmin;
                minIndex = d;

                NSLog(@"minIndex = %d", minIndex);

            }
        }

2 个答案:

答案 0 :(得分:2)

试试这样:

NSCalendar* calendar = [NSCalendar currentCalendar];

NSDateComponents* components = [calendar components:NSDayCalendarUnit fromDate:[NSDate date]];// Get necessary date components
[components day]; //gives you day

编辑为您只需要日期。您可以设置NSYearCalendarUnit | NSMonthCalendarUnit |如果你也想要年月值。

答案 1 :(得分:0)

使用相同的日期格式化程序再次格式化dayFromString,您将得到您期望的结果

 NSLog(@"Date %@", [dayFormatter stringFromDate: dayFromString]);  

这不是你想要的。 NSDateFormatter用于格式化日期。

[dayFormatter dateFromString:dayString];

将返回一个NSDate对象。如果您没有通过字符串提供所有值,它将使用参考时间填充缺失值。所以你得到的输出不是错误。如果您想从日期中获取一些组件(日,小时......),请使用 NSDateComponents 。 NSDateFormatter仅用于格式化日期。