1

I'm trying to display date and time of selected time zone from uipicker in a label or text field I'm not getting any way to solve this problem, so please any one help me Thanks in advance.

SelectedTimeZone= [Weight objectAtIndex:[pickerView selectedRowInComponent:0]]; NSString *selectedzone = SelectedTimeZone;

NSCalendar *gregorian=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithName:selectedzone]];
NSDateComponents *timeZoneComps=[[NSDateComponents alloc] init];

NSDate *date=[gregorian dateFromComponents:timeZoneComps];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterFullStyle];
[formatter setDateFormat:@"dd-MM-yyyy HH:mm:ss "];
NSString *todaysDate= [formatter stringFromDate:[NSDate date]];
zone.text = todaysDate;  I know this is not proper way but i'm new to xcode
Muddu Patil
  • 91
  • 2
  • 12

2 Answers2

3

[NSDate date]returns a date object representing the current date and time, no matter where you are. NSDates are not subject to places or time zones. There is just one NSDate that represents now or any other moment for that matter, not different date objects for every time timezone. Therefore, you should not attempt to convert a date between time zones.

NSDate *now = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Australia/Sydney"]];
NSLog(@"%@",[formatter stringFromDate:now]); //--> 9/9/11 11:54 PM
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Paris"]];
NSLog(@"%@",[formatter stringFromDate:now]);

Or Refer same question here

Community
  • 1
  • 1
Muddu Patil
  • 91
  • 2
  • 12
0

To get date and time of selected time zone from uipicker provide date to formatter like this:

NSDate *now = [NSDate date];
NSCalendar *gregorian=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithName:selectedzone]];

NSDateComponents* timeZoneComps = [gregorian components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSTimeZoneCalendarUnit fromDate:now];

NSDate *selectedDate=[gregorian dateFromComponents:timeZoneComps];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterFullStyle];
[formatter setDateFormat:@"dd-MM-yyyy HH:mm:ss "];
NSString *strSelectedDate= [formatter stringFromDate:selectedDate];
zone.text = strSelectedDate;
Paresh Navadiya
  • 38,095
  • 11
  • 81
  • 132