iOS7如何根据指定的时区获取当前时间和日期?

时间:2014-03-16 05:40:13

标签: ios timezone nsdate nsdateformatter nsdatecomponents

iOS编程:我只想让iOS7获得" America / Chicago"当前日期和时间。 我在互联网上搜索了很多,但有很多不同的解决方案。我尝试了几种解决方案,但它们不起作用。

3 个答案:

答案 0 :(得分:3)

您可以使用NSCalendar和NSTimezone类。以下代码段演示了检索当前小时和分钟。扩展它以检索其他日期组件是直截了当的 -

long hour;
long minute;
NSCalendar *cal=[NSCalendar currentCalendar];
NSDate *now=[NSDate date];
NSTimeZone *tz=[NSTimeZone timeZoneWithName:@"America/Chicago"];

[cal setTimeZone:tz];
NSDateComponents *comp=[cal components:NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:now];
hour=[comp hour];
min=[comp minute];

答案 1 :(得分:2)

您可以使用此方法

- (NSDate *) getCountryDateWithTimeZone:(NSString *)zone
{

    NSDate *now = [NSDate date];
    NSTimeZone *szone = [NSTimeZone timeZoneWithName:zone];

    NSInteger sourceGMTOffset = [szone secondsFromGMTForDate:now];
    NSTimeInterval interval = sourceGMTOffset;
    NSDate *destinationDate = [NSDate dateWithTimeInterval:interval sinceDate:now];

    return destinationDate;
}

而且,

[self getCountryDateWithTimeZone:@"America/Chicago"];

答案 2 :(得分:1)

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSString *firstDate = @"2014-06-05 12:55:00";

NSDate *date=[dateFormatter dateFromString:firstDate];

NSDate *currentDate = [NSDate date];

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:date toDate:currentDate options:0];

NSLog(@"The difference between from date and to date is %d days and %d hours and %d minute and %d second",components.day,components.hour,components.minute,components.second);

输出:

  

DateBookApp [1179:70b]日期和日期之间的差异是0天22小时57分12秒