NSDate format issue

天涯浪子 提交于 2020-01-11 07:49:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!