tags:

views:

155

answers:

1

hi guys - hopefully a quick one for someone! I am struggling to see why the code below isn't working. I am trying to get today's date (eg: 2010-09-10) and manually adding the time. It always seems to return 00:00:00 for the time though. any ideas where I'm going wrong?

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd";

NSString *actualDate = [dateFormatter stringFromDate:[NSDate date]];
NSDate *sDate = [dateFormatter dateFromString:[NSString stringWithFormat:@"%@ %@", actualDate, @"01:00:00"]];
NSDate *eDate = [dateFormatter dateFromString:[NSString stringWithFormat:@"%@ %@", actualDate, @"23:59:59"]];

The NSDate objects are returning the format 2010-09-10 00:00:00 +01:00 all the time. Somewhere it's just not picking up the time.... any ideas? many thanks.

* UPDATE *

The code below works. I did as suggested and accessed the elements and updated them.

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDate *date = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd hh:mm:ss";

//update for the start date
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
NSDate *sDate = [calendar dateFromComponents:comps];

//update for the end date
[comps setHour:23];
[comps setMinute:59];
[comps setSecond:59];
NSDate *eDate = [calendar dateFromComponents:comps];
+1  A: 

You should use NSCalendar instead then. It allows you to parse the current date and modify its components. Like you can initialize it with today's date and then set the time and then get an NSDate from it.

(Old answer: Because your formatter is configured to only recognize the date part. Add the time part to it (even though its name is NSDateFormatter, it will happily parse dates and times) and you will see the time too.)

St3fan
Even when I add the hh:mm:ss, I do get the time, but I'm not interested in that. I need to simply get today's date, then create two new NSDates from that. A start date of today's date and the time 00:00:00 and the end date of today's date and the time 23:59:59. As per my code, I was hoping to ONLY get the date. I'm not interested in the time... I want to GIVE the new NSDate the times I specified.
Matt Facer
Thanks St3fan.. I've updated my post with new code.
Matt Facer
I just re-read your post and actually did what you said! Sorry.. it's working now. Will update the code in mine to show it working
Matt Facer