ios - 将日期从时区转换为设备本地时区和日期

标签 ios timezone nsdate nsdateformatter

如何将时区 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/

相关文章:

ios - 我如何在 iOS 中实现 "snooze"?

iphone - 需要 iOS 核心数据架构技巧

ios - 使用 Swift 仅向文本添加高亮/背景

angular - 如何在 angular5 中将 Local 转换为 UTC,将 UTC 转换为 Local?

ios - UIScrollView 崩溃

Java - 将带有时区的unix时间(以毫秒为单位)转换为时间戳

MySQL格式问题

IOS 如何将日期与另一个日期进行比较?

Swift NSDate 扩展错误 : Mutating isn't valid on methods in classes or class-bound protocols

date - NSDate 从 Swift 2.3 到 Date 从 Swift 3 转换