Pregunta

I was trying to build a datepicker program on iPhone. However, the time showed in text is earlier exactly 8 hour than the time I choose. Here's the code.

"h"file:

#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"file:

#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;
}
¿Fue útil?

Solución

Convert selected date to your local timezone

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];

Otros consejos

From reading your comments, nothing is wrong, its just showing a different Timezone than you expected. NSDate to string by default goes to GMT/UTC time.

Use an NSDateFormatter to control the timezone being output: Apple Documentation for NSDateFormatter

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top