嗨,我的应用程序中有一个倒计时计时器,我正在寻找一种方法来获取我的时间戳日期,并根据时区对其进行修改,而无需格式化。时间戳是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之前添加时区代码,然后根据时区更改该数字(保持时间戳)。这可能吗?谢谢
试试这个:
//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]);
愿它对你有用。
快乐编码。。。
使用NSDateFormatter获取日期对象的正确时区。
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setTimeZone:[NSTimeZone localTimeZone];
NSTimeZone
具有属性secondsFromGMT
。因此,您可以使用[NSTimeZone systemTimeZone].secondsFromGMT;
来获得差异,将其添加到时间间隔中并实例化日期。
格式化NSDate以调整时区:
NSTimeZone *tz = [[NSTimeZone timeZoneForSecondsFromGMT:(-8 * 3600)];
[dateFormatter setTimeZone:tz];
NSString* s = [dateFormatter stringFromDate:now];