Question

I get the date and time with this void:

-(void)getDay
{

NSDate *choice = [NSDate date];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];

[dateFormatter setDateFormat:@"yy"];
year = [[dateFormatter stringFromDate:choice] intValue];

[dateFormatter setDateFormat:@"MM"];
month = [[dateFormatter stringFromDate:choice] intValue];

[dateFormatter setDateFormat:@"dd"];
day = [[dateFormatter stringFromDate:choice] intValue];


[dateFormatter setDateFormat:@"HH"];
hour = [[dateFormatter stringFromDate:[NSDate date]] intValue];

//   NSLog(@"hour: %d",hour);

[dateFormatter setDateFormat:@"mm"];
minute = [[dateFormatter stringFromDate:[NSDate date]] intValue];

[dateFormatter setDateFormat:@"ss"];
second = [[dateFormatter stringFromDate:[NSDate date]] intValue];

}

if I see the log hour... it gives me the right hour in my local time, but when I put that value in another NSDate that I need to create the hour change and become the Greenwich time, here's the code I use:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:SS"];
   // NSLog(@"hour: %d",hour);
  //this log still gives me the right hour

    [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];

    self.myDate = [dateFormatter dateFromString:[NSString stringWithFormat:@"%d-%d-%d %d:%d:%d",day,month,year,hour,minute,second]];
  NSLog(@"my date: %@",myDate);

This last log looks like this:

2013-08-31 05:14:12.905 myApp[25987:904] my date: 2013-08-31 15:14:00 +0000

my hour should be 5:14 but instead it is 15:14 that is Greenwich time... Why is this happening and how can I get the local time and not the Greenwich one? Thanks for any help.

Was it helpful?

Solution

There is nothing wrong with your code. The problem is that NSLog displays the date in GMT time. Try to put a breakpoint in the NSLog and you will see that self.myDate has the correct time whereas the NSLog displays the time in GMT.

I realized that in the formatter string you are using SS for the seconds. You have to use ss.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top