【发布时间】:2019-05-15 14:47:10
【问题描述】:
我有以下方法,它将给定时间(以 UTC 为单位)作为参数,并以“更友好的格式”将其转换为当前时间。
有效/正常的输入可能是:'11:30' 或 '1:30' 我的问题是虽然我的设备中设置的时区是纽约(-4 GMT),甚至这个例子中的硬编码!此函数不断将时间转换为 -5 GMT(分别为上午 6:30 和晚上 8:30)
-(NSString*) convertServerTimeToAppTimeFormat:(NSString*) input {
NSDateFormatter *dateFormatInput = [[NSDateFormatter alloc] init];
[dateFormatInput setDateFormat:@"HH:mm"];
[dateFormatInput setTimeZone :[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *date = [dateFormatInput dateFromString:input];
NSDateFormatter *dateFormatInputOutput = [[NSDateFormatter alloc] init];
[dateFormatInputOutput setDateFormat:@"h:mm a"];
[dateFormatInputOutput setTimeZone: [NSTimeZone localTimeZone]];
[dateFormatInputOutput setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
return [dateFormatInputOutput stringFromDate:date];
}
肯定有一些我没有看到的非常明显的东西。我通常会使用:
[NSTimeZone localTimeZone]
要获取我的用户所在的当前时区,而不是像我在这里所做的那样对其进行硬编码,但我认为硬编码版本应该有助于使错误更加明显。
【问题讨论】:
标签: objective-c time nsdateformatter datetime-conversion