0

I want to get the date today, and set the hour to a user-input value. I tried this:

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);

Though 'remind' is set to the expected value (current date with the hour set to the desired value of the 'hour' variable), whereas 'remindOn' is set to the current date. Why is that? Am confused. The output is this: First reminder set on: 2012-06-11 04:30:00 +0000 , str: 2012-6-11 10:00:00

Say, if 'hour' value is '10', I want 'remindOn' to be set to 2012-06-11 10:00:00 i.e. today's date, but the 'time' is set to '10'

Jean
  • 2,611
  • 8
  • 35
  • 60

1 Answers1

2

NSLog will log the date as GMT date, if you want to print out a more accurate date use NSDateFormatter method stringFromDate:

Like this

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

So dont NSLog the date directly since it will return it as GMT time zone

Omar Abdelhafith
  • 21,163
  • 5
  • 52
  • 56