0

我不明白为什么我的“小时”是 3。我期待 9。对我所缺少的任何见解。

NSDate* sourceDate = [NSDate date];

NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"CST"];

NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

NSDate *currentTimeConvertedToHQTime = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
NSLog(@"currentTimeConvertedToHQTime = %@", currentTimeConvertedToHQTime);

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH"];
int hour = [[dateFormatter stringFromDate:currentTimeConvertedToHQTime] intValue];
[dateFormatter release];

///日志

2012-08-20 08:55:13.874 QTGSalesTool[3532:707] currentTimeConvertedToHQTime = 2012-08-20 09:55:10 +0000
2012-08-20 08:55:13.878 QTGSalesTool[3532:707] hour = 3
4

1 回答 1

0

NSDateFormatter在这里可能没用。相反,NSCalendar在您需要的时区构造一个对象,然后获取NSDateComponents当前时间:

NSDate* currentDate = [NSDate date];

// Create a calendar that is always in Central Standard Time, regardless of the user's locale.
NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CST"]];
// The components will be in CST.
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:currentDate];

NSLog(@"currentDate components = %@", components);
NSLog(@"currentDate hour = %ld", [components hour]);

// Test for 9:00am to 5:00pm range.
if (([components hour]>=9) && ([components hour]<=12+5))
{
    NSLog(@"CST is in business hours");
}

有关其强大功能的更多信息,请参阅NSCalendar 类参考。例如,您可以测试周末。只要确保您请求您需要的单位(NSWeekdayCalendarUnit在这种情况下)。

NSDateComponents *components =[calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSWeekdayCalendarUnit) fromDate:currentDate];
NSLog(@"currentDate components = %@", components);
NSLog(@"currentDate weekday = %ld", [components weekday]);

// Test for Monday to Friday range.
if (([components weekday]>1) && ([components weekday]<7))
{
    NSLog(@"Working day");
}
else
{
    NSLog(@"Weekend");
}
于 2012-08-21T06:38:38.367 回答