根据时区更新倒计时时间戳

时间:2013-11-22 07:44:26

标签: ios objective-c nsdate

您好我的应用程序中有倒数计时器,我正在寻找一种方法来获取我的时间戳日期并根据时区修改它而不进行格式化。时间戳是GMT,它看起来像这样:

theDate = [NSDate dateWithTimeIntervalSince1970:1387929601];

然后我在这里有我的倒计时格式化器:

-(void)updateCountdownText
{
        //Update the Countdown Label
        NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
        int units =  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
        NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:theDate options:0];
        [dateLabel setText:[NSString stringWithFormat:@"%d%c %d%c %d%c %d%c", [components day], 'd', [components hour], 'h', [components minute], 'm', [components second], 's']];

    }

由于我已经格式化了下面的时间戳,我想要做的就是获取GMT时间戳编号并根据当地时区进行转换。所以我只想在dateWithTimeInterval之前添加时区代码,然后根据时区更改该数字(保持时间戳)。这可能吗?谢谢!

4 个答案:

答案 0 :(得分:1)

试试这个:

        //Timestamp convert to NSDate
        double time=[myString doubleValue];//in yourcase mystring=@"1387929601"; mystring is timestamp
        NSTimeInterval interval =time ;
        NSDate *online = [NSDate dateWithTimeIntervalSince1970:interval];
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter setDateFormat:@"hh:mm a dd-MMM-yyyy"];
        NSLog(@"Timestamp date is: %@", [dateFormatter stringFromDate:online]);

        NSString *mystr=[dateFormatter stringFromDate:online];
        NSCalendar *cal = [NSCalendar currentCalendar];
        NSDate *now = [dateFormatter dateFromString:mystr];

        value1=([[NSTimeZone localTimeZone] secondsFromGMT]);
        value1=value1/3600;
        float value123=((value1) * 3600);

        NSTimeZone *tz = [NSTimeZone timeZoneForSecondsFromGMT:(value123)]; // for PST
        NSDateComponents *dc = [cal components: NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit   fromDate:now];
        [cal setTimeZone:tz];

        NSDate *newDate = [cal dateFromComponents:dc];
        NSDateFormatter *dateFormatter1 = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter1 setDateFormat:@"hh:mm a dd-MMM-yyyy"];

        NSLog(@"result: %@", [dateFormatter1 stringFromDate:newDate]);

愿它适合你。

快乐的编码......

答案 1 :(得分:0)

使用NSDateFormatter获取theDate对象的正确时区。

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setTimeZone:[NSTimeZone localTimeZone];

答案 2 :(得分:0)

NSTimeZone有一个属性secondsFromGMT。因此,您可以使用[NSTimeZone systemTimeZone].secondsFromGMT;来获取差异,将其添加到您的时间间隔并实例化日期。

答案 3 :(得分:0)

格式化NSDate以调整时区:

World
相关问题