简体   繁体   中英

NSDateFormatter not returning the correct date

I have the following code which is used to take the time of one NSDate and the current date and combine them into one NSDate. However the formatters are set correctly, but it's returning a date that isn't even close to the one it should be. Here is the code

/* Get the current date and make a formatter to just show the date ONLY */
NSDate *currentDate = [NSDate date];
NSDateFormatter *curDateFormatter = [[NSDateFormatter alloc] init];
[curDateFormatter setDateFormat:@"MM/dd/YYYY"];

/* Create a formatter for the time ONLY */
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:@"hh:mm"];

/* Create a formatter for both date and time */
NSDateFormatter *combinedFormatter = [[NSDateFormatter alloc] init];
[combinedFormatter setDateFormat:@"MM/dd/YYYY hh:mm"];

NSString *combinedDateTime = [NSString stringWithFormat:@"%@ %@", [curDateFormatter stringFromDate:currentDate], [timeFormatter stringFromDate:time]];
NSDate *combinedDate = [combinedFormatter dateFromString:combinedDateTime];

/* release the formatters */
[curDateFormatter release];
[timeFormatter release];
[combinedFormatter release];

return combinedDate;

Say it is doing it when this message was posted, it should have 11/10/2010 06:47 but instead it's like 12/27/2009 11:45. Does this in the simulator and the device.

Instead of using the combinedDateFormatter, try the following:

    NSDate *combinedDate = [NSDate dateWithNaturalLanguageString:combinedDateTime];

This worked fine for me.

Value for combinedDateTime string was 09/27/2011 11:55

Value for combinedDate date object was 2011-09-27 11:55:00 +0530

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM