NSDate错误的一年

时间:2014-05-08 08:33:15

标签: ios objective-c nsdate

我正在尝试使用NSDate并且它不适合我,我现在很困惑。所以我想要的基本工作,但它需要是今天的日子而不是2000年。

所以我想要的是Date应该是今天的日期,其中包含我的字符串 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
}

1 个答案:

答案 0 :(得分:0)

我已经找到了马丁从帖子中给出的方法问题的答案。这种方法可以转换&#34;时间&#34;字符串(18:00)到今天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];
}