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