Reputation: 1110
I hope this isn't GMT related or I will feel rather stupid.
2 quick related questions. Why is this converting to a different date? Is losing a day. I looked at time zones as stated in other answers but it is always the GMT timezone 0000 which is what I expected. I presume the error is in my setDateFormat but I can't see how to fix it.
NSString *stringFromDate = self.dateLabel.currentTitle;
NSLog(@"StringFromDateWeight! %@", stringFromDate);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
//Convert Back to NSDate
[df setDateFormat:@"ddMMyyyy"];
NSDate *inputedDate = [df dateFromString: stringFromDate];
NSLog(@"StringFromDateWeight2! %@", inputedDate);
NSLog(@"StringFromDateWeight! %@", stringFromDate);
is
17072013
NSLog(@"StringFromDateWeight2! %@", inputedDate); is
2013-07-16 23:00:00 +0000
I am also using the code below to compare 2 dates and am I right in that it returns in seconds? How would I change it to return in days?
int intervall = (int) [theDate timeIntervalSinceDate: now];
Upvotes: 0
Views: 618
Reputation: 90117
If you don't explicitly set a timezone NSDateFormatter
will use your local timezone. You don't set one, so your formatter will create a NSDate that is at "midnight July 17" in your timezone. The description
method of NSDate will return a date that is formatted in UTC timezone. Since you get "July 16 23:00:00" I guess your timezone is UTC+1.
You have two options. Calculate in UTC by setting the timezone explicitly.
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
Or, usually more useful, don't look at the description
of NSDate and use [inputedDate descriptionWithLocale:[NSLocale currentLocale]]
for debugging, which will print the date formatted for your timezone.
If you want to display the date to the user use another NSDateFormatter
(preferably with dateStyle and timeStyle and not dateFormat, because hardcoded dateFormats are evil)
It's just the display that is different, the underlying NSDate object is still the same.
Regarding your second question:
In many timezones there are 2 days each year that don't have 24 hours, so you can't calculate anything with the seconds you get from timeIntervalSinceDate:
.
You have to use NSDateComponents
and NSCalendar
. Fortunately there is already a method that does exactly what you want. components:fromDate:toDate:options:
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:inputedDate toDate:[NSDate date] options:0];
NSLog(@"Date was %d days (and %d hours, %d minutes and %d seconds) ago", components.day, components.hour, components.minute, components.second);
If you only need the number of days you can remove all components except NSDayCalendarUnit
Upvotes: 4