2013-11-22 131 views
0

嗨我的应用程序中有一个倒数计时器,我正在寻找一种方法来取我的时间戳日期,并根据时区对其进行修改而不进行格式化。时间戳是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之前添加时区代码,然后根据时区更改该数字(保留时间戳)。这可能吗?谢谢!

+0

你为什么不使用'NSDateFormatter',您将免费获得正确的时区和格式选项? – Pfitz

回答

0

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

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

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

1

试试这个:

 //Timestamp convert to NSDate 
     double time=[myString doubleValue];//in yourcase [email protected]"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]); 

可能会为你工作。

快乐编码...

0

格式化的NSDate调整时区:

NSTimeZone *tz = [[NSTimeZone timeZoneForSecondsFromGMT:(-8 * 3600)]; 
[dateFormatter setTimeZone:tz]; 
NSString* s = [dateFormatter stringFromDate:now];