如何将时区 1 的日期转换为设备本地时区 2 的日期?
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Jerusalem"]];
NSDate *date = [dateFormat dateFromString:timestamp];
then something like:
[dateFormat2 setTimeZone:[NSTimeZone localTimeZone]];
date2 = [dateFormat2 dateFromDate:date withOtherTimeZone:zone];
更新:
我想我明白了。
//get source date from the server
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSDate *sourceDate = [dateFormat dateFromString:timestamp];
//set timezones
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Jerusalem"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
//calc time difference
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
//set current real date
NSDate* date = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
可以吗?
最佳答案
好的,时间到了。就在这一秒,地球上到处都是同一秒。不要再将时间格式视为时间。它不是。所有时间都应该是格林威治标准时间,然后你可以根据时区显示它。
Date *d = [NSDate date] ;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss Z"];
NSTimeZone *nyTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"sometimeabbr."];
NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone];
[df setTimezone: nyTimeZone];
NSLog(@"ny time is %@" , [df stringFromDate: d]);
[df setTimeZone: localTimeZone];
NSLog(@"local time is %@" , [df stringFromDate: d]);
如果给定一个字符串日期并需要转换,请创建 NSDateFormatter 以获取字符串日期。确保设置时区。现在你有了一个 NSDate 对象(NSDates 中没有时区),你可以将它格式化为你想要的任何其他时区。
请为爱一切圣洁。将时间视为向前推进的秒数,将时区视为这些时区的格式。
关于ios - 将日期从时区转换为设备本地时区和日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21028804/