如何使用目标c获取明天早上6点的日期?

时间:2011-03-06 20:29:59

标签: objective-c nsdate

您好 这是我的问题。 鉴于今天的日期,我必须得到明天的日期,但时间应该设定为早上6点。 我使用NSDate和NSDateComponents。但它总是在早上6点增加5小时,NSDate返回总是在上午11点。我在这做错了什么? 这是我的代码:

//1. Get today's date
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone defaultTimeZone]];
NSLog(@"1 Today %@", today);

//2. Get tomorrow's date
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate: today options:0];
NSLog(@"2 nextDate %@", nextDate);

//3. Get the data components for tomorrow's date to set the time
NSDateComponents *nextDateComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:nextDate];
NSInteger theDay = [nextDateComponents day];
NSInteger theMonth = [nextDateComponents month];
NSInteger theYear = [nextDateComponents year];

//4. Build tomorrow's date with time at 6am
NSDateComponents *tomorrowComponents = [[NSDateComponents alloc] init];
[tomorrowComponents setDay:theDay];
[tomorrowComponents setMonth:theMonth];
[tomorrowComponents setYear:theYear];
[tomorrowComponents setHour:6];
NSDate *tomorrow = [gregorian dateFromComponents:tomorrowComponents];
NSLog(@"3 Tomorrow %@", tomorrow);
[gregorian release];

3 个答案:

答案 0 :(得分:1)

您需要使用正确的区域设置格式化要记录的日期以转换为字符串。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
NSLocale *enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
[dateFormatter setLocale:enUSPOSIXLocale];
dateFormatter.dateFormat = @"MM-dd-yyyy h:mm a";
NSLog(@"3 Tomorrow %@", [dateFormatter stringFromDate:tomorrow]);
[dateFormatter release];

答案 1 :(得分:0)

您似乎忘了复制时区。

答案 2 :(得分:0)

这是一个时区问题。你将时间设置为当地时间早上6点,但返回GMT。