-3

What I'm trying to do is have an NSDate with the correct current time. When I convert the date into a string the time is correct, but when I'm converting back to an NSDate, the time is just off.

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm"];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSDate* myDate = [dateFormatter dateFromString:dateString];
NSLog(@"datete:%@ and %@", myDate, dateString);

2014-02-22 00:18:00 +0000 and 21-02-2014 16:18

Bomiz
  • 9
  • 3

1 Answers1

0

When printing NSDate objects, remember that description returns the date in UTC. So if you see a difference between the two objects, make sure you take into account your timezone and add that to the printed value of the NSDate.

When you want to correctly print them in your logs and/or UI, you should use a date formatter, rather than printing the NSDate object directly. Date formatters take the local timezone and system locale, and print the dates correctly.

Léo Natan
  • 56,823
  • 9
  • 150
  • 195
  • How would I go about adding the correct amount? It's different for different timezones – Bomiz Feb 22 '14 at 00:20
  • @Bomiz I meant add in your head so you can check for correctness. `NSDate` objects do not hold any timezone information. When you want to correctly print them in your logs and/or UI, you should use a date formatter, rather than printing the `NSDate` object directly. – Léo Natan Feb 22 '14 at 00:21
  • What I am doing is Saving the current date as a userdefault. I cannot save the formatter. So what I thought was to convert it back into an NSDate for it to save. But would it be possible to convert the NSString with the correct date to an NSDate containing the same date as the string? – Bomiz Feb 22 '14 at 00:25
  • @Bomiz Uhm, why are you converting an `NSDate` object into anything? It can be saved in user defaults as is. See documentation: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html#//apple_ref/doc/uid/20000318-CIHDHAGB – Léo Natan Feb 22 '14 at 00:26
  • Sorry, disband this question. What was messing with me was some completely different block of code that I fixed. Thank you though!!! – Bomiz Feb 22 '14 at 00:37