简体   繁体   English

获取iPhone中两个特定时区之间的时差?

[英]Get time difference between two specific time zones in iPhone?

例如,我想要亚洲/加尔各答时间与亚洲/迪拜之间的时差。

NSInteger differenceInSeconds = [timeZone1 secondsFromGMT] - [timeZone2 secondsFromGMT];

Note that this gives the current time difference between those timezones. 请注意,这给出了这些时区之间的当前时差。 If the two timezones observe daylight savings at different times of year, the time difference depends on when you evaluate this. 如果两个时区在一年的不同时间观察到夏令时,则时差取决于您对此进行评估的时间。 If this matters to you, you should use secondsFromGMTForDate: to get the timezone offset at a specific date. 如果这对您很重要,则应使用secondsFromGMTForDate:获取特定日期的时区偏移量。

NSDate *now = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc] init] ;
[df setTimeStyle:NSDateFormatterFullStyle];
[df setTimeZone:[NSTimeZone timeZoneWithName:Str]];//str = timezone1(for you its kolkata)
[df setDateFormat:@"dd-MM-yyyy HH:mm"];
NSString *S1 = [df stringFromDate:now];
[df setDateFormat:@"dd-MM-yyyy HH:mm"];
NSDate *dd = [df dateFromString:S1];
//dd = date1 as per timezone
NSLog(@"dd > %@",dd);

[df release];


NSDate *dt = [NSDate date];
NSLog(@"dt = %@",dt);
NSDateFormatter *df1 = [[NSDateFormatter alloc] init];
[df1 setTimeStyle:NSDateFormatterFullStyle];
[df1 setTimeZone:[NSTimeZone timeZoneWithName:Str2]];//str2=timezone2(for you its dubai)
[df1 setDateFormat:@"dd-MM-yyyy HH:mm"];

NSString *S2 = [df1 stringFromDate:dt];

[df setDateFormat:@"dd-MM-yyyy HH:mm"];
NSDate *dd1 = [df dateFromString:S2];
//dd1 = date2 as per timezone
NSLog(@"dd1 > %@",dd1);


NSCalendar *sysCalendar = [NSCalendar currentCalendar];
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;

NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:dd  toDate:dd1  options:0];

NSLog(@"Conversion: %dmin %dhours %ddays %dmoths",[conversionInfo minute], [conversionInfo hour], [conversionInfo day], [conversionInfo month]);

i'm usin this code and its working properly. 我在这段代码中使用,并且可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM