UIDatePicker giving wrong time [duplicate]

烈酒焚心 提交于 2019-12-08 04:30:35

问题


Possible Duplicate:
Getting date from [NSDate date] off by a few hours
NSDate date don’t give me the right hour

I have this piece of code:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm"];

NSString *formattedDateInString = [formatter stringFromDate:[self.datePicker date]];
NSLog(@"This is the formatted date (STRING) ---> %@" ,formattedDateInString);
self.fromHourLabel.text = formattedDateInString;

NSDate *date = [formatter dateFromString:formattedDateInString];
NSLog(@"This is the date (NSDate) ---> %@" ,date);
self.fromHour = date;

I basically get the date from a UIDatePicker, set Hours and Minutes as a label text and save the date into a property called fromHour. In the -viewDidLoad method I also have:

self.datePicker.timeZone = [NSTimeZone localTimeZone];

This is the output:

as you can see, with this code, I have two main problems:

  • The first output say 17.30 and the second 16:30 (the first output is correct, the second is wrong) why?
  • The second output is formatted with "yyyy-MM-dd HH:mm:ss" but I need only "HH:mm".

Can you help me?


回答1:


I know there are dozens of existing questions that cover this but I can't find one.

The problem is simple. When you print an object using NSLog or a string format containing the %@ format specifier, the description method is called on the object.

The description method of NSDate always displays the full date using the Zulu timezone (+0000).

If you want a date printed in a specific format then use NSDateFormatter to convert to a string and print the string.

Edit: Based on info from the comments, part of the problem here is that you start with the proper NSDate. You then convert that to a string with the format HH:mm. You then create a new NSDate from that string. The better solution is to simply save the original date and avoid the creation of the 2nd date.



来源:https://stackoverflow.com/questions/14550249/uidatepicker-giving-wrong-time

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