0

我试图在 iPhone 上构建一个 datepicker 程序。但是,文本中显示的时间比我选择的时间早 8 小时。这是代码。

“h”文件:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
    UIDatePicker *datepick;
    IBOutlet UILabel *label;
    IBOutlet UITextField *textfield; 
}
-(IBAction)button;
@property (nonatomic, retain)IBOutlet UIDatePicker *datepick;
@end

“m”文件:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize datepick;

-(IBAction)button {
    NSDate *choice = [datepick date];
    NSString *words = [[NSString alloc]initWithFormat:@"The date is %@", choice];

    UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"the title" message:words
    delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil, nil];
    [alert show];
    label.text = words;
    textfield.text = words;
}
4

2 回答 2

1

将所选日期转换为您当地的时区

NSDate *choice = [datepick date];

NSDateFormatter *dateFormat = [[NSDateFormatter new] autorelease];
[dateFormat setTimeZone:[NSTimeZone localTimeZone]];
[dateFormat setDateFormat:@"yyyy-MM-dd h:mma"];

NSString *strDate = [dateFormat stringFromDate:choice];
于 2012-06-14T19:01:39.453 回答
0

从阅读您的评论来看,没有错,只是显示的时区与您预期的不同。默认情况下,NSDate 到字符串转到 GMT/UTC 时间。

使用 NSDateFormatter 来控制输出的时区:Apple Documentation for NSDateFormatter

于 2012-06-14T19:00:39.363 回答