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 に答える