1

I have this piece of code. I get the current date and time and keep the day/month/year part, changing the time.

The first thing I notice is that the current date and time is wrong. One hour before the correct time. Then, I change the time to my own time and it is wrong again.

This is the code:

NSDate *today = [NSDate date];
// now is june 28, 17:39 pm, printing this to console gives me 
// june 28, 16:39 pm... one hour before... this is the first problem

// then I change the time...

// get the current day, month and year
NSCalendar * gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

NSDateComponents *dayX = [gregorian  components: NSDayCalendarUnit fromDate: data];
NSDateComponents *monthX = [gregorian  components: NSMonthCalendarUnit fromDate: data];
NSDateComponents *yearX = [gregorian  components: NSYearCalendarUnit fromDate: data];

NSInteger day = [dayX day];
NSInteger month = [monthX month];
NSInteger year = [yearX year];

// this gives me the correct day, month and year
// now, create a new date using the current day, month and year but with new hour and minute...


NSDateComponents * dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setHour:17];
[dateComponents setMinute:32];
[dateComponents setDay:day];
[dateComponents setMonth:month];
[dateComponents setYear:year];

// the new date is: 16:32????? 
// how can that be if I just set it 17:32??????????

any clues?

thanks

Steve
  • 31,144
  • 19
  • 99
  • 122
Duck
  • 34,902
  • 47
  • 248
  • 470

1 Answers1

2

Time Zones:

Answered on this post: NSDateComponents returning strange hour

[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
Community
  • 1
  • 1
Steve
  • 31,144
  • 19
  • 99
  • 122
  • but how do I solve that if I don't know the user's time zone? – Duck Jun 28 '11 at 16:52
  • http://stackoverflow.com/questions/1268509/convert-utc-nsdate-to-local-timezone-objective-c – Steve Jun 28 '11 at 16:55
  • In your example, what time zone is the device set to? – Dan F Jun 28 '11 at 16:55
  • 3
    The app have to be able to convert any time zone, depending on the user's timezone. Why Apple does that? is it that difficult to provide a method that can give the current, real, time the clock is marking on the user's device? Do have to call a NASA engineer to calculate the volumetric integral of the third derivative to have the correct hour? This is insane! Sorry for the rant, but all I need is the current real correct time. :( – Duck Jun 28 '11 at 17:06
  • http://stackoverflow.com/questions/4322687/why-nscalendars-datefromcomponents-returns-wrong-date – Steve Jun 28 '11 at 17:17