问题
Here is the code from the nsdate formatter... for some reason the value dateSelected is incorrect... instead of "April 30 2011 7:55PM" it returns 2011-05-01 02:55... any idea what am i doing wrong?
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"h:mm a"];
objEventInsert.eventtime = [outputFormatter stringFromDate:self.datePicker.date];
NSLog(@"%@",objEventInsert.eventtime);
NSDateFormatter *dateForm = [[NSDateFormatter alloc] init];
[dateForm setDateFormat:@"LLLL d y h:mm a"];
NSDate *dateSelected = [dateForm dateFromString:[NSString stringWithFormat:@"%@ %@",objEventInsert.eventstartdate,objEventInsert.eventtime]];
NSLog(@"%@",objEventInsert.eventstartdate);
objEventInsert.date = dateSelected;
NSLog(@"%@",objEventInsert.date);
NSLog response...
2011-04-30 19:54:14.264 APP[24017:207] 7:55 PM
2011-04-30 19:54:16.216 APP[24017:207] April 30 2011
2011-04-30 19:54:17.654 APP[24017:207] 2011-05-01 02:55:00 +0000
回答1:
That's the correct UTC time. You'll need to set the locale/timezone to get the local time, i.e. 7:55.
See these answer examples
- Inconsistent behaviour with NSDateFormatter on two different devices
- NSDate dateFromString, how to parse 'around' UTC, GMT and User locale?
回答2:
Your problem is that you create a new NSDate again and you just initiate it through a string. So either your should create a string in your last step or your need to reuse the NSDateFormatter.
NSString *dateSelected = [NSString stringWithFormat:@"%@ %@",objEventInsert.eventstartdate,objEventInsert.eventtime];
NSLog(@"%@", dateSelected);
Note: can use appendStringByFormat to make your code less verbose.
来源:https://stackoverflow.com/questions/5846144/nsdate-format-issue