开发者

iphone NSDate - get todays date and force the time

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 se开发者_开发百科tMinute:59];
[comps setSecond:59];
NSDate *eDate = [calendar dateFromComponents:comps];


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.)


I found this question today while looking to do the same thing, create an NSDate with a specific time today. The solution presented wasn't quite what I needed so I came up with this:

NSDate *                date;
NSString *              string, *timestamp;
NSDateFormatter *       formatter;

timestamp = @"17:30";

formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat: @"yyyy-MM-dd "];
[formatter setTimeZone: [NSTimeZone localTimeZone]];

string = [formatter stringFromDate: [NSDate date]];
string = [string stringByAppendingString: timestamp];

[formatter setDateFormat: @"yyyy-MM-dd HH:mm"];
date = [formatter dateFromString: string];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜