将NSDate转换为本地时区,检查“今天”或“明天”并在NSString中获取日期

时间:2015-05-27 02:16:59

标签: ios objective-c

我之前已经问过类似的问题,但我的情况略有不同,我一直在努力寻找解决方案。

我的代码是这样做的:

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];

现在我有一个问题。例如:

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

如您所见,NSString与我明确转换为local timezone的日期不一致。当我使用'isDateInToday'方法时,这也会导致问题。我在这里错过了什么?注意:我的本地时区设置为PST

2 个答案:

答案 0 :(得分:5)

我发布这是Swift,但由于问题是关于API的正确使用而不是Objective-C,这有望起到与伪代码相同的作用,对您有用。基本上,您将时间转换两次,一次通过减去间隔,一次通过在格式化程序中指定TZ。

转换为NSDate

let time:NSTimeInterval = 1432028287411/1000
let date = NSDate(timeIntervalSince1970: time)

Formatter以UTC / GMT显示结果

let utcFormatter = NSDateFormatter()
utcFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
utcFormatter.dateFormat = "hh:mm:ss zzz"

格式化程序以在当前时区显示结果,即PDT

let currentTzFormatter = NSDateFormatter()
currentTzFormatter.timeZone = NSTimeZone.defaultTimeZone()
currentTzFormatter.dateFormat = "hh:mm:ss zzz"

显示GMT / UTC时间

utcFormatter.stringFromDate(date)

显示PDT(本地TZ)时间

currentTzFormatter.stringFromDate(date)

检查日期是否为今天(在本地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.

答案 1 :(得分:0)

您的代码唯一的问题是时区。以下是它应该如何显示的大致轮廓:

var localPlaceholder = document.getElementById('localFiles');
for (i=0; i<entries.length; i++) {
    var newList = document.createElement( "li" );
    newList.nodeValue = entries[i].name;
    localPlacholder.appendChild(newList);
}