在 SQLite 中存储 NSDate 在 GMT 中检索和显示显示,需要在创建时显示原始时区的时间

Storing NSDate in SQLite retrieving and displaying shows in GMT, need to display time in original timezone it was created in

当用户创建新记录时,我将 NSDate 存储在具有本地时区(例如 PST)的 SQLite 中。当从 DB 中检索到相同的 NSDate 时,时间被视为 GMT(这是可以理解的,因为 NSDate 没有时区的概念并且是绝对的)。

我想根据创建时区的时间显示 NSDate - 例如,如果 NSDate 存储在 PST 时区,之后用户移动到美国东北部,我仍然希望能够从数据库中检索 NSDate 并以太平洋标准时间(而不是美国东部时间)显示时间。我是否应该在创建记录时存储本地时区,以便在显示时间时使用该时区?

这是我的代码,如有任何帮助,我们将不胜感激。

NSDate *date = xxxxxxxxxxx; // This is retrieved from DB
NSDateFormatter *format = [[NSDateFormatter alloc] init];
format.dateFormat = @"MM/dd/yyyy hh:mm:ss";
NSString *timeStr = [format stringFromDate:date];
NSLog(@"Time :%@",timeStr);

你说:

Should I store the local time zone when the record is created, so that that timezone is used in displaying the time?

是的,这是一种方法:将时区信息保存在数据库的单独字段中。所以,在保存日期的时候,除了在数据库中写上GMT日期外,在一个单独的字段中,保存当前时区的名称:

NSString *timeZoneName = [NSCalendar currentCalendar].timeZone.name;

(注意,我没有使用 abbreviation,因为它们不是唯一的。)

然后,从数据库中检索日期和时区名称后,使用NSDateFormatter以正确的格式输出日期:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeZone = [NSTimeZone timeZoneWithName:timeZoneName];
formatter.dateFormat = @"MM/dd/yyyy hh:mm:ss a z";
NSString *timeString = [formatter stringFromDate:date];

顺便说一下,请注意我在我的格式字符串中使用了 a(AM/PM)指示符(因为您没有使用 HH 表示小时)。

坦率地说,如果你想对国际用户友好,我会避免使用 dateFormat 并使用 dateStyletimeStyle

formatter.dateStyle = NSDateFormatterShortStyle;
formatter.timeStyle = NSDateFormatterLongStyle;