开发者

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


Take a look at below URL;

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜