2013-11-22 98 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];