Sapozhnick
Sapozhnick

Reputation: 91

How to specify a time zone in UIDatePicker

- (IBAction) buttonPressed {
NSDate *selected = [datePicker date];
NSString *message = [[NSString alloc] initWithFormat:@"The date and time you selected is: %@", selected];
UIAlertView *alert = [[UIAlertView alloc]
                      initWithTitle:@"Date and Time Selected" message:message delegate:nil cancelButtonTitle:@"Yes, I did!" otherButtonTitles:nil];
[alert show];
[alert release];
[message release];

So my question is next... How can I specify a time zone using a Datepicker in Objective C? now if I choose some values from DatePicker and press the button which displays an alert - the time is wrong. It's probably because of incorrect time zone but I'm not sure. Well any ideas would be great. On the picture below you can see that I chose 2:14 PM (14:14) but an alter says that it is 11:14 and the time zone is +000

UPDATE 1 I have added a few changes to my code but still nothing...

- (IBAction) buttonPressed {
NSDate *selected = [datePicker date];       
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    
NSTimeZone *tz = [NSTimeZone systemTimeZone];
[dateFormatter setTimeZone:tz];
NSString *formattedDate = [dateFormatter stringFromDate:selected];
NSString *message = [[NSString alloc] initWithFormat:@"The date and time you selected is: %@", formattedDate];
UIAlertView *alert = [[UIAlertView alloc]
                      initWithTitle:@"Date and Time Selected" 
                      message:message delegate:nil cancelButtonTitle:@"Yes, I did!" otherButtonTitles:nil];
[alert show];
[alert release];
[message release];
[dateFormatter release];

Upvotes: 9

Views: 18173

Answers (5)

Bhadresh
Bhadresh

Reputation: 417

You can set the date with timezone

Objective C

datePicker.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:10*60*60]; // Like GMT+10

in Swift 3:

datePicker.timeZone = TimeZone(secondsFromGMT: 5*60*60)  // Like GMT+5

Upvotes: 6

Wilson
Wilson

Reputation: 9136

in Swift 3:

datePicker.timeZone = NSTimeZone.local

Upvotes: 5

rampurearun
rampurearun

Reputation: 41

You can set the date with timezone strings like Australia/West (+08:00) , WST, Asia/Kolkata (+05:30) , IST

datePicker.timeZone = [NSTimeZone timeZoneWithName:@"timezone string goes here"] ;

Upvotes: 2

Avik Roy
Avik Roy

Reputation: 187

Use this at the point where use defined your datepicker

datePicker.timeZone = [NSTimeZone localTimeZone];

Upvotes: 17

Daniel
Daniel

Reputation: 22395

I think this is because of the date format being picked, use an NSDateFormatter to specify the appropriate date format and use it in your string, here is a link Link

Upvotes: 1

Related Questions