How to "round" minutes and hours - iphone

I did not really know on how to title this question so hopefully you've find the way in :)
My Problem is:
I wanted to set a clock time for a label with a UISlider.
So basically my slider min value is 0000 and the max value is 2400. (24 hour format)
So how do I achieve a properly formatted clock?
For example if my slider's value is at (1161)11:61 it should be (1201)12:01 and so on.
Any tipps for that :)
Would be great to get some help here.
Thanks to all who participate.

why don't you start from 0 to 1440. (24 hours = 1440 minutes) and do something like below.
int hours = slider.value / 60; -> no of hours;
int minutes = slider.value %60; -> no of minutes;
NSString *clock = [NSString stringWithFormat:#"%d : %d", hours, minutes];

You could do this with an NSDateComponents object. Create one, then break up your slider value into two parts: the thousands and hundred digits become the hour, and the tens and ones digits become the minute. You can feed this object to an NSCalendar to transform it into an actual NSDate (if that's what you want).

Related

How can validate NSDATE

How to find one text field value is within past 60 day excluding current date.
For example if I enter value in text field is 20-July-2012 using Date Picker.Then I click submit,it'll check that specific is date is within 60 days or not. If the values are entered which is before 60 days an alert message is displayed. The values are retrieved from api.
NSDate *today = [NSDate date];
NSTimeInterval dateTime;
if ([pickerDate isEqualToDate:today]) //pickerDate is a NSDate
{
NSLog (#"Dates are equal");
}
dateTime = ([pickerDate timeIntervalSinceDate:today] / 86400);
if(dateTime < 0) //Check if visit date is a past date, dateTime returns - val
{
NSLog (#"Past Date");
}
else
{
NSLog (#"Future Date");
}
Change the value of 86400 to suit your query.In this case, it is the number of seconds we want to compare.
First, convert the text into an NSDate. Then use
timeIntervalSinceDate:[NSDate dateWithTimeIntervalSinceNow:0]
There are a couple of ways to convert text into an NSDate. You can format the text correctly and then use dateWithString or you can convert everything into numbers, multiply them out, and one of the dateWithTimeInterval methods.
If you want the user to be able to enter "July" (plain text month) then you might want to write a method that converts months into their numerical equivalents with string matching.
NSDate *lastDate; //your date I hope you have created it
NSDate *todaysDate = [NSDate date];
NSTimeInterval lastDiff = [lastDate timeIntervalSinceNow];
NSTimeInterval todaysDiff = [todaysDate timeIntervalSinceNow];
NSTimeInterval dateDiff = lastDiff - todaysDiff; // number of seconds
int days = dateDiff/(60*60*24); // 5.8 would become 5 as I'm taking int
How do you define 60 days?
You may want to use NSCalendar -dateByAddingComponents:toDate:options: to ensure your 60 days really are 60 days.
NSCalendar also provides -components:fromDate: and -dateFromComponents: which are very nice when dealing with date components.
If 60 days do not need to be true calendar days (daylight saving time switches, astronomical time corrections, stuff like that), you can just have fun with NSDate and the time interval methods alone.

Convert integer number to time format

How can I convert an integer such as 115900 to a time? I'd like to do arithmetic operations on times so that something like: 115900 + 100 will equal 120000, rather than 11600.
Your big problem is that an integer number does not behave like a date/time. Since you are using Objective-C, you really should be using the NSDate class and the associated classes for formatting dates and times and managing calendars.
Start by reading the Date and Time Programming Guide. That will be better than me writing it all out again.
int seconds = 115900 % 60;
int minutes = (115900 / 60) % 60;
int hours = 115900/ 3600;
return [NSString stringWithFormat:#"%02i:%02i:%02i",hours, minutes, seconds];
//output like is HH:MM:SS

objectiveC/CMTime - convert AVPlayer.duration to milliseconds

I'm creating an app for playing a ringtone and I'd want to know the current time in milliseconds of the played ringtone every time.
CMTime cTime = player_.currentTime;
float currentTime = cTime.value / cTime.timescale;
That currentTime here gets the value in seconds.
How can I get the exact currentTime value but in milliseconds?
There is a way to get current times in seconds, you can take 1000 times that and ther you have your miliseconds:
Float64 dur = CMTimeGetSeconds([player currentTime]);
Float64 durInMiliSec = 1000*dur;
Sadly you will have to use it as a float or Float64 you can't use that result as a CMTime
I think that the accepted answer loses detail. A more accurate way to get milliseconds would be the following:
let seconds : Double = Float64(time.value * 1000) / Float64(time.timescale)
If you convert to seconds first you'd lose precision.
CMTime.value and CMTime.timescale are both integers, so judging by your code, the result gets rounded and you don't get a precise timestamp. Try CMTimeGetSeconds instead.

how to get amout of ticks for a reference date on the iphone

I'm programming against a Webservice that requires the amount of ticks (for the current time) (A single tick represents one hundred nanoseconds or one ten-millionth of a second) since 1.1.0001 (midnight).
what is the easiest way to get the amount of ticks from an NSDate Object?
thanks for your help
Just make 1.1.0001 into an NSDate and then use the NSDate method timeIntervalSinceNow and multiply by 10 million.
This code will give you GMT time.
const long long UNIX_EPOCH_IN_CLR_TICKS = 621355968000000000 ;
long long time = UNIX_EPOCH_IN_CLR_TICKS + [[NSDate date] timeIntervalSince1970] * pow(10, 7);

Memory Leaks - Formatting a String To Display Time, Each Second

Hey guys. I have a method that gets called each second which I want to use to display the time that my app has been doing it's work. Currently the class I'm using (Which I did not create) has a property named progress which stores the total number of seconds.
I have already written some code which takes these seconds and formats it into a readable string. I'm new to this, so pardon me if it's not the best code. I welcome any suggestions:
// hours, minutes, and seconds are instance variables defined as integers
int totalSeconds = (int)streamer.progress;
hours = totalSeconds / (60 * 60);
if (hours > 0)
formattedTimeString = [NSString stringWithFormat:#"%d:", hours]; // WRONG
minutes = (totalSeconds / 60) % 60;
seconds = totalSeconds % 60;
[formattedTimeString stringByAppendingFormat:#"%d:%d", minutes, seconds]; // WRONG
Basically I want it to appear as "3:35" for example to show 3 minutes, 35 seconds. I only want to show the hour section if it has been an hour, in which case it would be "2:3:35" for example (Can anyone recommend a better way to format this?).
The problem I am having is where I actually create/set the string (The lines tagged WRONG). Since this is being done every second, I would easily get a leak if I keep asking for a new string object. I figure I can solve this by releasing the foramttedTimeString at the end of the method, but is this the correct way to accomplish this? Would an NSMutableString help in any way? Is there a better, Cocoa way of doing this? I already asked in #iphonedev # freenode and they said I would have to write this method myself, but I figured I'd ask again.
To provide context: this is an internet radio streaming app (I know there are many already, but I'm just practicing). I want to be able to show the amount of time the stream has been playing for.
Sorry if this question is stupid, heh, like I said I'm new to this.
I would do it something like:
int totalSeconds = (int)streamer.progress;
hours = totalSeconds / (60 * 60);
minutes = (totalSeconds / 60) % 60;
seconds = totalSeconds % 60;
if ( hours > 0 ) {
formattedTimeString = [NSString stringWithFormat:#"%d:%02d:%02d", hours, minutes, seconds];
} else {
formattedTimeString = [NSString stringWithFormat:#"%d:%02d", minutes, seconds];
}
Now at the end, formattedTimeString is the desired time, but you do not "own" it - you must retain it, or store it in a "copy" property if you wish to keep it around.
Note that the %02d gives you a guarenteed two digits, zero filled number, which is usually what you want for numbers in parts of times.
To see how you would do it with stringByAppendingFormat, it would look something like this:
NSString* formattedTimeString = #"";
if ( hours > 0 ) {
formattedTimeString = [formattedTimeString stringByAppendingFormat:#"%d:", hours];
}
formattedTimeString = [formattedTimeString stringByAppendingFormat:#"%d:%02d", minutes, seconds];
However in this case, you'll get times like 3:4:05, rether than a more desirable 3:04:05.
Note that formattedTimeString is being overwritten each time, but that is OK bvecause you do not "own" it at any time, so you are not responsible for releasing it.
Finally, to see it with a mutable string, it might look like this:
NSMutableString* formattedTimeString = [NSMutableString string];
if ( hours > 0 ) {
[formattedTimeString appendFormat:#"%d:", hours];
}
[formattedTimeString appendFormat:#"%d:%02d", minutes, seconds];
Again, the time result is the undesirable 3:4:05, and again you do not own formattedTimeString at the end, so it must be retained or stored with a copy property to keep it around.
For knowing the deltas as time units, you can also do something like this:
// as part of init...
self.gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// in the timer or wherever you are tracking time deltas...
static NSUInteger unitFlags =
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:myBaseTime
toDate:[NSDate date] options:0];
Then you can reference the parts with something like this [components minute].
Remember, you'll have to release the calendar in dealloc.
Your code looks pretty good. You're not leaking any memory because the string objects you create have a retain count of zero and will be cleaned up by the system. However, if formattedTimeString is not a local variable in your function, you need to retain it at the end to prevent this from happening! To do that, you would add [formattedTimeString retain] to the end of your code block, and then before replacing the string object you would add [formattedTimeString release].
As a general rule, functions with names containing "alloc", "copy", "create", and "new" return objects that have already been retained, (meaning their retain count is +1). It's your responsibility to call release or autorelease on these objects when you're done using them - or they will just start piling up in memory.
Functions like "stringWithFormat:", "imageNamed:", and "arrayWithCapacity:" all return objects with a retain count of zero - so you can safely discard them (as you are in the code sample). If you want to keep them around, you should call retain to make sure they are not cleaned up while you're using them.
All that said, I think the main problem is your use of stringByAppendingFormat:. Since the NSString you're using isn't mutable, that call returns a new string. You'd want to say:
formattedTimeString = [formattedTimeString stringByAppendingFormat:#"%d:%d", minutes, seconds];
Alternatively, you could use an NSMutableString. Since this is something you'll be doing over and over again, I'd recommend doing that. Technically, either way is fine though.
Hope that helps! The whole retain/release thing can get confusing. Just remember that each object has a "retainCount" and once it hits zero there's no telling what happens to the object or it's data.
Hey thanks guys I appreciate the responses.
I ended up doing this, and it works, but I would like to know if you guys see any problems with it:
int totalSeconds = (int)streamer.progress;
[formattedTimeString setString:#""];
hours = totalSeconds / (60 * 60);
if (hours > 0)
[formattedTimeString appendFormat:#"%d:", hours];
minutes = (totalSeconds / 60) % 60;
seconds = totalSeconds % 60;
[formattedTimeString appendFormat:#"%02d:%02d", minutes, seconds];
And then of course in viewDidLoad I instantiate the instance variable formattedTimeString:
formattedTimeString = [[NSMutableString alloc] initWithCapacity:8];
I did not do any retaining/releasing in the first code snippet because I didn't think it was necessary, but I could be wrong. I am, however, releasing in the dealloc method, so I should be fine there.