Objective C Convert int to NSString (iPhone)
I have the following code that is meant to convert milliseconds into hours, mins and seconds:
int hours = floor(rawtime / 3600000);
int mins = floor((rawtime % 3600000) / (1000 * 60));
int secs = floor(((rawtime % 3600000) % (1000 * 60)) / 1000);
NSLog(@"%d:%d:%d", hours, mins, secs);
NSString *hoursStr = [NSString stringWithFormat:@"%d", hours];
NSString *minsStr = [NSString stringWithFormat:@"%d", mins];
NSString *secsStr = [NSString stringWithFormat:@"%d", secs];
NSLog(@"%a:%a:%a", hoursStr, minsStr, secsStr);
Fairly straightforward. Rawtime is an int with value 1200. The output is lik开发者_运维知识库e this:
0:0:1
0x1.3eaf003d9573p-962:0x1.7bd2003d3ebp-981:-0x1.26197p-698
Why is it that converting the ints to strings gives such wild numbers? I've tried using %i and %u and they made no difference. What is happening?
You have to use %@
as the conversion specifier for an NSString. Change your last line to:
NSLog(@"%@:%@:%@", hoursStr, minsStr, secsStr);
%a
means something totally different. From the printf()
man page:
aA
The double argument is rounded and converted to hexadecimal notation in the style[-]0xh.hhhp[+-]d
where the number of digits after the hexadecimal-point character is equal to the precision specification.
Instead of rolling your own string formatting code, you should be using an NSNumberFormatter
for numbers or an NSDateFormatter
for dates/times. These data formatters take care of localization of format to the user's locale and handle a variety of formats built-in.
For your use, you need to convert your millisecond time into an NSTimeInterval
(typedef
'd from a double):
NSTimeInterval time = rawtime/1e3;
Now you can use an NSDateFormatter
to present the time:
NSDate *timeDate = [NSDate dateWithTimeIntervalSinceReferenceDate:time];
NSString *formattedTime = [NSDateFormatter localizedStringFromDate:timeDate
dateStyle:NSDateFormatterNoStyle
timeStyle:NSDateFormatterMediumStyle];
NSString *rawTime = [[formattedTime componentsSeparatedByString:@" "] objectAtIndex:0];
on OS X where the last line removes the "AM/PM". This will work for any time less than 12 hrs and will give a formatted string in the localized format for HH:MM:SS. On the iPhone, localizedStringFromDate:dateStyle:timeStyle:
isn't available (yet). You can achieve the same effect with setTimeStyle:
, setDateStyle:
and stringFromDate:
on a date formatter instance.
精彩评论