-2

I'm trying to get the current date with :

NSLog(@"DATE NOW : %@", [NSDate date]);

But when I execute it, I have a difference of one hour between the date displayed and the current date.

Log http://data.imagup.com/12/1171458807.5637png

I found topics on questions like that but none of them gave me the answer. How can I change that ?

Seb
  • 545
  • 9
  • 29

1 Answers1

3

You need to set the proper timezone. The default, as you can see, is UTC.

You can use a date formatter for doing that.

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone * timezone = [NSTimeZone timeZoneWithName:@"Europe/Rome"];
[dateFormatter setTimeZone:timezone];
[dateFormatter setTimeStyle:NSDateFormatterFullStyle
 ];
[dateFormatter setDateStyle:NSDateFormatterFullStyle];    


NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]);

For a list of available timezones you can use

NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames];

or check out the constants here on this Rails doc page.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
  • 3
    The date is an abstraction. What you want is to display it correctly, and you can do that with a date formatter. – Gabriele Petronella Dec 29 '12 at 15:23
  • I added the style setting for date and time, so it now prints something like `Saturday, December 29, 2012, 4:28:25 PM Central European Standard Time`. Clearly you can customize that. – Gabriele Petronella Dec 29 '12 at 15:29
  • @Gabrielle : I don't want to print it, I want to set it to a property of a custom NSObject. – Seb Dec 29 '12 at 15:37
  • 1
    @Seb Store it like it is. NSDate contains the timezone information (the trailing `+0000`) so whenever you need to display it just format it and you're good. `NSDate` is a model, whereas its formatting (timezone, style, whatever) is purely a visualization matter. And by the way my name has just one "l" in it :P – Gabriele Petronella Dec 29 '12 at 15:46
  • Indeed, it gave me : "heure normale de l’Europe centrale / 2012-12-29 16:47:02 +0000", thanks. But how can I convert it to a date ??? – Seb Dec 29 '12 at 15:47
  • Refer to my last comment. The only reason you may want to change the timezone is to display it. If you don't need to do that, you're good. – Gabriele Petronella Dec 29 '12 at 15:49