0
//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);

编辑:

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

//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);

            }
        }
4

2 回答 2

2

试试这样:

NSCalendar* calendar = [NSCalendar currentCalendar];

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

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

于 2013-05-16T10:40:12.990 回答
0

使用相同的日期格式化dayFromString程序再次格式化,你会得到你所期望的

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

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

[dayFormatter dateFromString:dayString];

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

于 2013-05-16T10:45:52.477 回答