Question

I am trying to work with NSDate and it is not working for me, I am so confused right now. So the basic thing I want works, but it needs to be the day of today and not from the year 2000.

So what I want is that the Date should be the date of today with the hours that are in my string bU and eU and not the date from the year 2000 with the hours of my string.

Here is a piece of my code:

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
}
Was it helpful?

Solution

I have found the answer to my problem with the method Martin has given from the post. This method converts an "Time" string like (18:00) to the date of today at 18:00.

Here it is:

- (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];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top