2014-05-08 33 views
-2

我想與NSDate合作,它不適合我,我現在很困惑。所以我想要的基本的東西工作,但它需要今天的日子,而不是從2000年。NSDate給出錯誤的一年

所以我想要的是,日期應該是今天的日期與我的字符串中的小時數bU和eU而不是2000年的日期和我的字符串的小時數。

以下是一段我的代碼:

NSDate *localNotDate; 

NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
[df setTimeZone:[NSTimeZone localTimeZone]]; 
[df setDateFormat:@"HH:mm"]; 

NSDate *bU = [df dateFromString:[[[self alarmArray] objectAtIndex:arrayInt] beginUur]]; // This is a 24:00 format string 
NSDate *eU = [df dateFromString:[[[self alarmArray] objectAtIndex:arrayInt] eindUur]]; // This is a 24:00 format string 

if (intForInsideForLoop == 0) { // Setup NSDate on first loop. 
    localNotDate = bU; // This gives the date 2000-01-01 08:24 
} 

if (intForInsideForLoop < timesOnDay) { 
    localNotDate = [localNotDate dateByAddingTimeInterval:(interval * 60)]; // Adds minutes to the date of today. 

    NSDateFormatter *dtest = [[NSDateFormatter alloc] init]; 
    [dtest setTimeZone:[NSTimeZone localTimeZone]]; 
    [dtest setDateFormat:@"yyyy-MM-dd HH:mm"]; 

    NSLog(@"%@", [dtest stringFromDate:localNotDate]); // This gives the date 2000-01-01 08:24. it should be like It's Today thursday so 2014-05-08 08:24 
} 
+2

也許你可以使用http://stackoverflow.com/a/20441330/1187415的第一部分。 –

+0

感謝他的工作! – Kets

回答

0

我已經找到了答案,我的問題與馬丁已經從後給出的方法。此方法將(18:00)的「Time」字符串轉換爲今天18:00的日期。

這就是:

- (NSDate *)todaysDateFromString:(NSString *)time 
{ 
    // Split hour/minute into separate strings: 
    NSArray *array = [time componentsSeparatedByString:@":"]; 

    // Get year/month/day from today: 
    NSCalendar *cal = [NSCalendar currentCalendar]; 
NSDateComponents *comp = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]]; 

    // Set hour/minute from the given input: 
    [comp setHour:[array[0] integerValue]]; 
    [comp setMinute:[array[1] integerValue]]; 

    return [cal dateFromComponents:comp]; 
}