【问题标题】:iOS7 how to get current time and date based on specified timezone?iOS7如何根据指定时区获取当前时间和日期?
【发布时间】:2014-04-21 10:06:24
【问题描述】:

iOS 编程:我只想让 iOS7 获取“美国/芝加哥”当前日期和时间。 我在互联网上搜索了很多,但有很多不同的解决方案。我尝试了几种解决方案,但都不起作用。

【问题讨论】:

  • 这是什么意思?日期与时区无关。仅当您希望向用户显示日期时才相关。请更好地描述您正在尝试做的事情。
  • @rmaddy - 有许多现实世界的场景与该陈述相矛盾。我认为您的意思是 NSDate 与时区无关,而不是通常的日期与时区无关。 :)
  • @MattJohnson 是的,我的意思是 NSDate。感谢您的澄清。

标签: ios timezone nsdate nsdateformatter nsdatecomponents


【解决方案1】:

您可以使用 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];

【讨论】:

    【解决方案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"];
    

    【讨论】:

    • 我可能错了,但我相信您还需要处理您的(设备的)时区。您正在计算 secondsFromGMT,而不是设备时区的秒数。
    • 好吧,我现在在我的程序中使用它。例如,如果 TimeZone 是 @"America/Chicago",[szone secondsFromGMTForDate:now];返回 -18000(-5 小时)并添加到现在日期(现在不是设备时区,它是 GMT 时间)。
    • 你是对的。我被NSLog 中的格式误导了。
    【解决方案3】:
    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 秒

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 2018-11-25
      • 2023-01-30
      • 2011-01-01
      • 2010-11-21
      • 2019-12-15
      相关资源
      最近更新 更多