0

我想获取今天的日期,并将小时设置为用户输入的值。我试过这个:

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
int year = [components year];
int month = [components month];
int day = [components day];
int hour = 10;
NSLog(@"%d %d %d", year, month, day);
NSString *yearStr   = [NSString stringWithFormat:@"%d", year];
NSString *monthStr  = [NSString stringWithFormat:@"%d", month];
NSString *dayStr    = [NSString stringWithFormat:@"%d", day];
NSString *hourStr   = [NSString stringWithFormat:@"%d", hour];
NSString *str1      = [yearStr stringByAppendingString:@"-"];
NSString *str2      = [str1 stringByAppendingString:monthStr];
NSString *str3      = [str2 stringByAppendingString:@"-"];
NSString *str4      = [str3 stringByAppendingString:dayStr];
NSString *str5      = [str4 stringByAppendingString:@" "];
NSString *str6      = [str5 stringByAppendingString:hourStr];
NSString *remind    = [str6 stringByAppendingString:@":00:00"];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *remindOn = [formatter dateFromString:remind];
NSLog(@"First reminder set on: %@ , str: %@", remindOn, remind);

虽然 'remind' 设置为预期值(当前日期,小时设置为 'hour' 变量的所需值),而 'remindOn' 设置为当前日期。这是为什么?我很困惑。输出是这样的:第一个提醒设置在:2012-06-11 04:30:00 +0000,str: 2012-6-11 10:00:00

说,如果“小时”值为“10”,我希望“提醒”设置为 2012-06-11 10:00:00,即今天的日期,但“时间”设置为“10”

4

1 回答 1

2

NSLog 会将日期记录为 GMT 日期,如果要打印出更准确的日期使用 NSDateFormatter方法stringFromDate:

像这样

NSDate *remindOn = [formatter dateFromString:remind];

//Instead of nslog directly, use this stringFromDate:remindOn
NSString *str = [formatter stringFromDate:remindOn];
NSLog(@"date is %@", str); //This will log the correct data

所以不要直接 NSLog 日期,因为它会将它作为 GMT 时区返回

于 2012-06-10T19:37:31.393 回答