日期转换问题

时间:2012-08-20 15:00:40

标签: objective-c ios

我不明白为什么我的“小时”出现为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

1 个答案:

答案 0 :(得分: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 Class Reference。例如,您可以测试周末。只需确保您要求所需的单位(在这种情况下为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");
}