0

Can any 1 help me to get this problem done I'm trying to display date and time of selected time zone n a label or text field I tried below code but its Displaying current time of system for all selected zone :( thanks in advance

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;
Nimit Parekh
  • 16,776
  • 8
  • 50
  • 72
Muddu Patil
  • 91
  • 2
  • 12

1 Answers1

1

[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]);
Muddu Patil
  • 91
  • 2
  • 12