Question

I've looked at the related questions with answers, their solutions have not worked. I'm really confused by the output I'm receiving from NSDateComponents and NSDateFormatter (and MTDates for ease of use but I've tried bypassing that to get different results to no avail).

Here is a link of the relevant section of the UI (from simulator): http://grab.by/rFbQ

As well as logs relevant to the issue:

2013-10-31 23:58:03.407 Application[22530:70b] Date 2013-11-01 04:58:03 +0000
2013-10-31 23:58:03.408 Application[22530:70b] Formatted Date Oct 31, 2013, 11:58:03 PM
2013-10-31 23:58:03.408 Application[22530:70b] Hours 17
2013-10-31 23:58:03.408 Application[22530:70b] Minutes 9

Code used to get the numbers:

[NSDate mt_setTimeZone:[NSTimeZone localTimeZone]];
NSDate *current = [NSDate date];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterMediumStyle];
[formatter setTimeZone:[NSTimeZone localTimeZone]];

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents *comp = [cal components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:current];

NSUInteger hours = comp.hour;
NSUInteger minutes = ceil([current mt_minuteOfHour] / 6);

NSLog(@"Date %@", current);
NSLog(@"Formatted Date %@", [formatter stringFromDate:current]);
NSLog(@"Hours %lx", hours);
NSLog(@"Minutes %lx", minutes);

self.dateLabel.text = [formatter stringFromDate:current];
self.timeLabel.text = [NSString stringWithFormat:@"%lx.%lx", hours, minutes];

I don't know if you could tell from the output above but the formatted date (for the correct timezone) shows the hour as "11" ("11:58:03") which baffles me when, even setting the timezone for the NSCalendar and NSDateFormatter to the same NSTimeZone (localTimeZone) I get "17" as the current hour.

I should also mention that I'm using MTDates to augment date actions but was encountering this issue before I included this library (hoping it's inclusion might somehow make these results more sane). That being said I've also tried replacing the portion where I fetch my own components with:

NSUInteger hours = [current mt_hourOfDay];

This, unfortunately, returns "17" as well. I would expect it to return "23" but would be happy with and "11" and could then figure out converting it to a 24 scale.

Was it helpful?

Solution

You are using the format specifier %lx which will format the numbers as hex values. You want %ld to get decimal (base 10).

See the String Programming Guide for some basic format specifiers.

See the IEEE spec for a complete list of the printf style format specifiers. Objective-C uses this spec with the addition of %@ for objects.

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