0

任何 1 都可以帮我解决这个问题吗我正在尝试显示所选时区的日期和时间 na 标签或文本字段我尝试了下面的代码,但它显示所有选定区域的系统当前时间:(提前致谢

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

1 回答 1

1

[NSDate date] 返回代表当前日期和时间的日期对象,无论您身在何处。NSDate 不受地点或时区的限制。只有一个 NSDate 代表现在或任何其他时刻,而不是每个时区的不同日期对象。因此,您不应尝试在时区之间转换日期。

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]);
于 2012-09-05T13:42:32.063 回答