如何从Xcode中的uipicker获取所选时区的日期和时间

时间:2012-08-27 11:36:33

标签: objective-c xcode xcode4

我正试图在标签或文本字段中显示选定时区的日期和时间我没有办法解决这个问题,所以请任何人帮我提前谢谢。

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

2 个答案:

答案 0 :(得分:3)

[NSDate date]返回表示当前日期和时间的日期对象,无论您身在何处。 NSDates不受地点或时区的限制。现在只有一个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]);

Refer same question here

答案 1 :(得分:0)

要从uipicker提供所选时区的日期和时间,请将日期提供给格式化程序,如下所示:

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;