Convert NSNumber (double) value into time - objective-c

i try to convert a value like "898.171813964844" into 00:17:02 (hh:mm:ss).
How can this be done in objective c?
Thanks for help!

Final solution:
NSNumber *time = [NSNumber numberWithDouble:([online_time doubleValue] - 3600)];
NSTimeInterval interval = [time doubleValue];
NSDate *online = [NSDate date];
online = [NSDate dateWithTimeIntervalSince1970:interval];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"HH:mm:ss"];
NSLog(#"result: %#", [dateFormatter stringFromDate:online]);

Assuming you are just interested in hours, minutes and seconds and that the input value is less or equal 86400 you could do something like this:
NSNumber *theDouble = [NSNumber numberWithDouble:898.171813964844];
int inputSeconds = [theDouble intValue];
int hours = inputSeconds / 3600;
int minutes = ( inputSeconds - hours * 3600 ) / 60;
int seconds = inputSeconds - hours * 3600 - minutes * 60;
NSString *theTime = [NSString stringWithFormat:#"%.2d:%.2d:%.2d", hours, minutes, seconds];

I know the answer has already been accepted, but here is my response using NSDateFormatter and taking into account timezone (to your timezone hours [eg. GMT+4] being unexpectedly added #Ben)
NSTimeInterval intervalValue = 898.171813964844;
NSDateFormatter *hmsFormatter = [[NSDateFormatter alloc] init];
[hmsFormatter setDateFormat:#"HH:mm:ss"];
[hmsFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSLog(#"formatted date: %#", [hmsFormatter stringFromDate:[NSDate dateWithTimeIntervalSinceReferenceDate:intervalValue]]);
[side note] #phx: assuming 898.171813964844 is in seconds, this would represent 00:14:58 not 00:17:02.

Convert your NSNumber value to a NSTimeInterval with -doubleValue
Convert your NSTimeInterval value to a NSDate with +dateWithTimeIntervalSinceNow:
Convert your NSDate to a NSString with -descriptionWithCalendarFormat:timeZone:locale:

Related

Problems with NSTimeInterval timeIntervalSinceDate

I want to code an alarm clock for iOS.
My code for calculating the difference between current time and alarm time:
NSDate *date = picker.date;
NSLog(#"[date description] %#",[date description]);
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:#"HH:mm:ss"]; //24h time format
NSString *dateString = [outputFormatter stringFromDate:picker.date];
NSLog(#"[date description] %#",dateString);
NSDate *startDate = [outputFormatter dateFromString:dateString];
NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];
NSDate *endDate = [dateFormatter dateFromString:resultString];
NSTimeInterval timeDifference = [endDate timeIntervalSinceDate:startDate];
double minutes = timeDifference / 60;
double hours = minutes / 60;
double seconds = timeDifference;
...which leads to these variables:
startDate = 2000-01-01 06:45:26 +0000
endDate = 2000-01-01 22:46:36 +0000
seconds = 57670 (= 16.01944 hours).
How to get to calculate the real time difference of 28740 seconds?
Just pass timeDifference in below method. It will give you Hours,Minutes and Seconds.
- (NSString *)timeFormatted:(int)totalSeconds{
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
return hours==0 ? [NSString stringWithFormat:#"%02d:%02d", minutes, seconds] : [NSString stringWithFormat:#"%02d:%02d:%02d",hours, minutes, seconds];
}
try below code:
Get time difference in hour, minutes,seconds from NSTimeInterval:
//.......
NSTimeInterval timeDifference = [endDate timeIntervalSinceDate:startDate];
long ti = lroundf(timeInterval);
int hour = ti / 3600;
int mins = (ti % 3600) / 60;
int secs = ti % 60;
OR
Get time difference in hour, minutes,seconds from Dates:
// Get the system calendar
NSCalendar *objCalendar = [NSCalendar currentCalendar];
// Create the NSDates
NSDate *currentTime = [[NSDate alloc] init];
NSDate *startDate = picker.date;
// Get conversion to months, days, hours, minutes
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *TimeInfo = [objCalendar components:unitFlags fromDate: currentTime toDate:startDate options:0];
NSLog(#" %dmin %dhours %ddays %dmoths ",[TimeInfo minute], [TimeInfo hour], [TimeInfo day], [TimeInfo month]);

Converting time to HH:MM

I currently have a float value like 12.5, 4, 17.5. I want these to correspond to the times 12:30PM, 4:00AM, and 5:30PM.
I've currently achieved something close to this with the hack
if (time > 12.5) {
time = abs(roundedValue - 12);
[lab setText:[NSString stringWithFormat:#"%i:00PM",(int)time]];
} else {
[lab setText:[NSString stringWithFormat:#"%i:00AM",(int)time]];
}
But I know this is bad practice. What's a better way to convert these numbers to times?
This is just basic math, you have a value, say 12.5, which consists of a number of hours, 12, and a fraction of an hour, 0.5. There are 60 mins in an hour so the number of minutes is just the fraction times 60.
If you want to use the 12 hour clock there is a small quirk, hours > 12 need to be reduced by 12 but noon (12) is pm and midnight (0 or 24) is am. So the test for am/pm is not the same test as whether to subtract 12.
Here is one way to do it (with minimal checking):
NSString *hoursToString(double floatHours)
{
int hours = trunc(floatHours); // number of hours
int mins = round( (floatHours - hours) * 60 ); // mins is the fractional part times 60
// rounding might result in 60 mins...
if (mins == 60)
{
mins = 0;
hours++;
}
// we haven't done a range check on floatHours, also the above can add 1, so reduce to 0 -> 23
hours %= 24;
// if you are using 24 hour clock you can finish here and format to the two values
BOOL pm = hours >= 12; // 0 - 11 = am, 12 - 23 = pm
if (hours > 12) hours -= 12; // 13 - 23 -> 1 -> 11
return [NSString stringWithFormat:#"%d:%02d %s", hours, mins, (pm ? "pm" : "am")];
}
You call this simply as:
hoursToString(13.1) // returns 1:06 pm
No need to use NSDate et al.
HTH
Solved by doing the following:
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
[components setHour:0];
NSDate *today10am = [calendar dateFromComponents:components];
NSDate *newDate = [NSDate dateWithTimeInterval:roundedValue*60*60 sinceDate:today10am];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"h:mm aa"];
[lab setText:[dateFormat stringFromDate:newDate]];
Sorry Hot Licks, guess this was within my comprehension.
You can use the following -
NSNumber *time = [NSNumber numberWithDouble:([yourTime doubleValue] - 3600)];
NSTimeInterval interval = [time doubleValue];
NSDate *yourDate = [NSDate date];
yourDate = [NSDate dateWithTimeIntervalSince1970:interval];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"HH:mm:ss"];
NSLog(#"result: %#", [dateFormatter stringFromDate:yourDate]);

Objective-C Xcode - if statement "Expected expression"

i must check if the interval between 2 times is > 0 then set the text of a label but i get "Expected expression" when i use the if statement..
NSDate * now = [NSDate date];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:#"HH:mm:ss"];
NSString *newDateString = [outputFormatter stringFromDate:now];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm:ss"];
NSDate *date1 = [df dateFromString:newDateString];
NSDate *date2 = [df dateFromString:#"15:00:00"];
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
int hours = (int)interval / 3600; // integer division to get the hours part
int minutes = (interval - (hours*3600)) / 60; // interval minus hours part (in seconds) divided by 60 yields minutes
int seconds = interval - ((hours*3600)+(minutes*60)) ;
NSString *timeDiff = [NSString stringWithFormat:#"%02d | %02d | %02d", hours, minutes, seconds];
if (interval < 0)
{
self.before3.text = timeDiff;
}
The error is on if (interval < 0)
Can someone help me please?
Regards.

NSTimeinterval problem for date in iphone sdk

I am converting the date into NSTimeinterval like the code below:
NSDate *currentDate = [NSDate date];
NSTimeInterval currentyInterval = [appDelegate setTimeInterval:currentDate];
NSDate *expiryDate = [appDelegate setReverseDate:warrObj.expiredOn];
NSTimeInterval expiryInterval = [appDelegate setTimeInterval:expiryDate];
//Here I am getting the nil value and exception is generated.
//It happens only in 3.1
-(NSTimeInterval )setTimeInterval:(NSDate *)selectedDate
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init] ;
[dateFormatter setDateFormat:#"dd-MMM-yyyy 00:00:00"];
NSString *currStr = [dateFormatter stringFromDate:selectedDate];
NSDate *newCurrentDate = [dateFormatter dateFromString:currStr];
NSTimeInterval timeInterval = [newCurrentDate timeIntervalSinceReferenceDate];
[dateFormatter release];
return timeInterval;
}
Can anyone suggest me how to get rid of this.
Thanks to all,
Madan.
NSTimeInterval is just a typedef for double, it is not an object:
Getting a time interval:
NSTimerInterval timeInterval = [[NSDate date] timeIntervalSinceReferenceDate];
NSDate *expiryDate = [appDelegate setReverseDate:warrObj.expiredOn];
NSTimeInterval expiryInterval = [expiryDate timeIntervalSinceReferenceDate];
Creating a date from a time interval:
NSTimeInterval oneHour = 60*60;
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval - oneHour];

NSNumber of seconds to Hours, minutes, seconds

I am having a terrible time trying to do something that should be easy. I have a NSNumber value of 32025.89 seconds. I need to represent that in Hours, Minutes, Seconds. Is there a method that spits that out? I can't seem to find a proper formatter.
Have you tried creating an NSDate from that and printing that using an NSDateFormatter?
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[theNumber doubleValue]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSLog(#"%#", [formatter stringFromDate:date]);
[formatter release];
If you need the individual values for hours, minutes, and seconds, use NSDateComponents as suggested by nall.
The above won't print the correct amounts if the NSNumber represents more than one day. It could be 1 day and 1 hour, and it would only print 01:00:00. In such a case you should calculate hours, minutes and seconds manually.
If you don't want to just divide it out, try this. It may be close enough for your purposes. Note: It doesn't account for sub-second precision. (setSecond takes an NSInteger).
NSDateComponents* c = [[[NSDateComponents alloc] init] autorelease];
[c setSecond:32025.89];
NSCalendar* cal = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]
autorelease];
NSDate* d = [cal dateFromComponents:c];
NSDateComponents* result = [cal components:NSHourCalendarUnit |
NSMinuteCalendarUnit |
NSSecondCalendarUnit
fromDate:d];
NSLog(#"%d hours, %d minutes, %d seconds",
[result hour], [result minute], [result second]);
Here's a way without any libraries except for modf() from math.h:
float fsec = 32025.89f, frac = 0;
int milliseconds = (int)(modf(fsec, &frac) * 1000);
int isec = (int)frac;
int hours = isec / 3600;
int minutes = (isec % 3600) / 60;
int seconds = isec % 60;
NSNumber *valueForDisplay = [NSNumber numberWithDouble:
[self valueForDisplay:clockName]];
NSNumber *totalDays = [NSNumber numberWithDouble:
([valueForDisplay doubleValue] / 86400)];
NSNumber *totalHours = [NSNumber numberWithDouble:
(([valueForDisplay doubleValue] / 3600) -
([totalDays intValue] * 24))];
NSNumber *totalMinutes = [NSNumber numberWithDouble:
(([valueForDisplay doubleValue] / 60) -
([totalDays intValue] * 24 * 60) -
([totalHours intValue] * 60))];
NSNumber *totalSeconds = [NSNumber numberWithInt:
([valueForDisplay intValue] % 60)];