我有一台服务器,它使用 NOW() 设置时间来存储 mySQL 数据库上用户之间发送数据的时间。 我正在尝试将时间转换为收件人的本地时间,但运气不佳(我会在存储之前转换时间,但正如我所说,我希望时间是收件人的本地时间,而不是发件人的本地时间)。 日期作为字符串返回到应用程序,我尝试按如下方式调整它:
NSString *string1 = [[receivedMessages objectAtIndex:thisRow]objectAtIndex:2];
NSDate *messageDate;
NSCalendar* cal = NSCalendar.currentCalendar;
NSTimeZone* tz = cal.timeZone;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM dd yyyy hh:mma"];
[formatter setTimeZone:tz];
messageDate = [formatter dateFromString:string1];
它确实对日期进行了格式化,但不正确。应用程序收到的日期为:
April 5 2012 5:49AM
转换为:
2012-04-05 04:49:00 +0000
我想知道 xcode 如何计算出日期首先属于哪个时区?
实际上,我刚刚再次使用它进行了测试
NSTimeZone *pst = [NSTimeZone timeZoneWithAbbreviation:@"PST"];
代替
NSCalendar* cal = NSCalendar.currentCalendar;
NSTimeZone* tz = cal.timeZone;
它仍然给我时间 2012-04-05 04:49:00 +0000。
大家有什么想法吗?
非常感谢
最佳答案
From the Apple docs , messageDate = [formatter dateFromString:string1];
将返回一个 NSDate。当您显示结果时,您正在打印一个 NSDate 对象,该对象(我猜测)已“字符串化”为 ISO 8601 date 。这些 NSDate 对象被标准化为绝对时间(没有时区信息)。
获得日期对象后,只需更进一步并格式化输出即可。我猜您显示的 tz 是原始时间,所以这很好(dateFromString
将转换为“绝对时间”)。您需要添加的只是类似 localizedStringFromDate:dateStyle:timeStyle: 的内容。获取本地时间。
//If this is not in UTC, we don't have any knowledge about
//which tz it is. MUST BE IN UTC.
dateString = "2012-03-12 9:53:23"
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM dd yyyy hh:mma"];
NSDate *date = [formatter dateFromString:dateString];
NSString *result = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle];
//The result should be in MY timezone automatically.
关于mysql - iOS - 将从 mySQL 服务器接收到的日期转换为用户本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10026714/