我之前已经问过类似的问题,但我的情况略有不同,我一直在努力寻找解决方案.
我有我的代码这样做:
NSDate *messageDate = [NSDate dateWithTimeIntervalSince1970:time / 1000];
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:messageDate];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:messageDate];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
// get final date in LocalTimeZone
NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:messageDate];
static NSDateFormatter *formatter;
static dispatch_once_t sOnce = 0;
dispatch_once(&sOnce, ^{
formatter = [[NSDateFormatter alloc] init];
});
[formatter setDateFormat:format];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *absTime = [formatter stringFromDate:destinationDate];
Run Code Online (Sandbox Code Playgroud)
现在我有一个问题.例如:
time = 1432028287411
messageDate = 2015-05-19 09:38:07 +0000
(NSInteger) currentGMTOffset = -25200
(NSInteger) gmtOffset = 0
destinationDate = 2015-05-19 02:38:07 +0000
absTime = Mon, May 18
Run Code Online (Sandbox Code Playgroud)
如您所见,这NSString与我明确转换为的日期不一致local timezone.当我使用'isDateInToday'方法时,这也会导致问题.我在这里错过了什么?注意:我的本地时区设置为PST.
我发布这是Swift,但由于问题是关于API的正确使用而不是Objective-C,这有望起到与伪代码相同的作用,对您有用.基本上,您将时间转换两次,一次通过减去间隔,一次通过在格式化程序中指定TZ.
转换为NSDate
let time:NSTimeInterval = 1432028287411/1000
let date = NSDate(timeIntervalSince1970: time)
Run Code Online (Sandbox Code Playgroud)
Formatter以UTC/GMT显示结果
let utcFormatter = NSDateFormatter()
utcFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
utcFormatter.dateFormat = "hh:mm:ss zzz"
Run Code Online (Sandbox Code Playgroud)
Formatter以在当前时区显示结果,即PDT
let currentTzFormatter = NSDateFormatter()
currentTzFormatter.timeZone = NSTimeZone.defaultTimeZone()
currentTzFormatter.dateFormat = "hh:mm:ss zzz"
Run Code Online (Sandbox Code Playgroud)
显示GMT/UTC时间
utcFormatter.stringFromDate(date)
Run Code Online (Sandbox Code Playgroud)
显示PDT(本地TZ)时间
currentTzFormatter.stringFromDate(date)
Run Code Online (Sandbox Code Playgroud)
检查日期是否为今天(在当地TZ)
let calendar = NSCalendar.currentCalendar()
calendar.isDateInToday(date) <- will show false today, because it is 26th today, not 19th, but will work correctly with today's date.
Run Code Online (Sandbox Code Playgroud)