How I can convert time of my JSON data to float value. Below code is written to convert time to float and I passed it to UISlider as total length of audio. I want to move slider with that time spans
//Json Data
{
duration = "00:03:45";
id = 8;
}
//Audio player sider bar function
if(audioController.playbackState == MPMusicPlaybackStatePlaying){
if (isSelected == YES) {
currentAutio = audioList[selectedAudio];
} else {
currentAutio = audioList[0];
}
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
float value = [numberFormatter numberFromString:currentAutio.duration].floatValue;
float currentPlaybackTime = [audioController currentPlaybackTime];
float TotalLength = value;
float remainingPlaybackTime = TotalLength - currentPlaybackTime;
float sliderPosition = (currentPlaybackTime *100) / TotalLength;
NSLog(#"current playbacktime %f",currentPlaybackTime);
NSLog(#"TotalLength %f",TotalLength);
NSLog(#"remainingPlaybackTime %f",remainingPlaybackTime);
NSLog(#"sliderPosition %f",sliderPosition);
//Update slider
[progressSlider setValue:sliderPosition];
//Update labels
NSDate* d1 = [NSDate dateWithTimeIntervalSince1970:currentPlaybackTime];
NSDate* d2 = [NSDate dateWithTimeIntervalSince1970:remainingPlaybackTime];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"mm:ss"];
NSString *currentTime = [dateFormatter stringFromDate:d1];
NSString *ramainingTime = [dateFormatter stringFromDate:d2];
[trackCurrentPlaybackTimeLabel setText:currentTime];
[trackLengthLabel setText:[NSString stringWithFormat:#"-%#",ramainingTime]];
}
I am getting following output:
Value = 0.00000
I don't think there is a built-in mechanism for converting a time interval into a float, but it's trivially easy to write:
func timeIntervalFrom(_ timeString: String) -> TimeInterval? {
//Add code to validate that string is in correct format
let components = time.components(separatedBy: ":")
guard components.count == 3,
let hours = Double(components[0]),
let minutes = Double(components[1]),
let seconds = Double(components[2]) else {
return nil
}
return hours * 3600 + minutes * 60 + seconds
}
Just convert the duration from String to integer components.
Then calculate the total duration in seconds.
You can get the integer components simply like this:
Swift
let timeComponents = duration.components(separatedBy: ":")
Objective C
NSArray *timeComponents = [duration componentsSeparatedByString:#":"];
timeComponents[0] will be the hours part.
timeComponents[1] will be the minutes part.
timeComponents[2] will be the seconds part.
Total seconds: (hours * 60 * 60) + (minutes * 60) + seconds.
After that, adjusting the slide bar value will be easy :)
Related
I wish to display HH:MM at a UILabel when I adjust a custom slider. Currently my custom slider is returning me float values, for example, 2.89, 24.87... I wish to take the float value say 24.87 and change it to 24:52 I got everything working at the following code but I think it is not the most efficient way. Can anyone improve it? Thank you
- (void)slideValueChanged:(id)control
{
NSLog(#"Slider value changed: (%.2f,%.2f)",
_rangeSlider.lowerValue, _rangeSlider.upperValue);
lblStart.text = [NSString stringWithFormat:#"Start Time : %#", [self floatToTime:_rangeSlider.lowerValue]];
lblEnd.text = [NSString stringWithFormat:#"End Time : %#",[self floatToTime:_rangeSlider.upperValue]];
}
- (NSString*)floatToTime:(float)floatTime {
NSInteger iHour = floatTime;
CGFloat floatMin = floatTime - iHour;
NSString *sHour = [NSString stringWithFormat:#"%li", (long)iHour];
if (floatMin == 0.99) { //=== When the float is 0.99, convert it to 0, if not 60*0.99 = 59.4, will never get to 0
floatMin = 0;
}else{
floatMin = floatMin * 60;
}
NSInteger iMin = floatMin; //=== Take the integer part of floatMin
NSString *sMin = [[NSString alloc] init];
if (iMin <10){ //=== Take care if 0,1,2,3,4,5,6,7,8,9 to be 00,01,02,03...
sMin = [NSString stringWithFormat: #"0%li", iMin];
}else{
sMin = [NSString stringWithFormat: #"%li", iMin];
}
NSString *strFloatTime = [NSString stringWithFormat:#"%#:%#", sHour,sMin];
return strFloatTime;
}
You can use a format to show two digits, this simplifies creating a time string:
CGFloat time = 24.87;
int hours = fabs(time);
int minutes = (int)((time - hours) * 60.0);
NSLog(#"Time: %02d:%02d", hours, minutes);
Result: "Time: 24:52"
'02' is the number of digits.
i know there are a lot of topics, but i canĀ“t find a solution for my problem.
i have an AVPlayerItem and i want the currentTime-property (CMTime) convert to a readable format for my music player.
this is my code:
NSDate *seconds = [[NSDate alloc] initWithTimeIntervalSinceNow:CMTimeGetSeconds(self.playerItem.currentTime)];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:#"HH:mm:ss"];
self.currentTimeLabel.text = [NSString stringWithFormat:#"%#", [timeFormatter stringFromDate:seconds]];
it works but it adds 1 hour to the played Time. how can i subtract that hour?
thx!
try this code,
swift code:
delclare
var playerVal = AVPlayer()
then call below method where you want,
func updateTime() {
let currentTime = Float(CMTimeGetSeconds(playerVal.currentTime()))
let minutes = currentTime/60
let seconds = currentTime - minutes * 60
startValue.text = NSString(format: "%.2f:%.2f", minutes,seconds) as String
}
objective-C code:
delclare
AVPlayer playerVal;
then call below method where you want,
- (void)updateTime {
Float currentTime = CMTimeGetSeconds([playerVal currentTime]);
Float minutes = currentTime/60;
Float seconds = (currentTime - minutes) * 60;
startValue.text = [NSString stringWithFormat:#"%.2f:%.2f", minutes,seconds];
}
its working for me, hope its helpful
thx, i refined it a bit:
float currentTime = CMTimeGetSeconds([self.audioStreamPlayer currentTime]);
int seconds = (int) currentTime;
int minutes = (int) currentTime/60;
int hours = (int) ((currentTime/60)/60);
NSString *hoursString = [NSString stringWithFormat:#"%d",hours];
NSString *minutesString = [NSString stringWithFormat:#"%d",minutes];
NSString *secondsString = [NSString stringWithFormat:#"%d",seconds % 60];
if (hoursString.length == 1) {
hoursString = [NSString stringWithFormat:#"0%d", hours];
}
if (minutesString.length == 1) {
minutesString = [NSString stringWithFormat:#"0%d",minutes];
}
if (secondsString.length == 1) {
secondsString = [NSString stringWithFormat:#"0%d", seconds % 60];
}
self.currentTimeLabel.text = [NSString stringWithFormat:#"%#:%#:%#", hoursString, minutesString, secondsString];
works!
I want the concatenated NSString I have to be output in the format "00:00", the 0s being the digits in the concatenated string. And if there are not enough characters in the NSString, the other digits are made to be 0.
And if there are more than 4 digits than I want to only have the furthest right digits.
I have done this in Java before, I am assuming it's possible in Objective-C as well.
UIButton *button = sender;
NSString *concatenated = [self.input stringByAppendingString: button.titleLabel.text];
self.input = concatenated;
self.userOutput.text = self.input;
For example, I might get "89" as my concatenated string. I then want, self.input = 00:89.
OR
if I get 89374374 from my concatenated string, I then want self.input = 43:74.
I hope I am being clear
The following method should give the desired output:
- (NSString *)getFormattedTimeStringFromString:(NSString *)string
{
int input = [string intValue];
int mins = input % 100;
input /= 100;
int hours = input % 100;
return [NSString stringWithFormat:#"%02d:%02d", hours, mins];
}
You can use this by calling
self.input = [self getFormattedTimeStringFromString:concatenated];
Like this:
NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm"];
NSString *dateTimeStr = [df stringFromDate:[NSDate date]];
if ([concatenated length] == 2) {
self.input = [NSString stringWithFormat:#"00:%#",concatenated];
}
else
{
NSString *test = [concatenated substringFromIndex:[concatenated length] -4];
self.input = [NSString stringWithFormat:#"%#:%#",[test substringToIndex:2],[test substringFromIndex:[test length]-2]];
}
Please try above code it will fail if [concatenated length] is 3 or 1 , modify it accordingly
I am receiving a string from the YouTube JSONC api, but the duration is coming as a full number i.e 2321 instead of 23:21 or 2 instead of 0:02. How would I go about fixing this?
JSON C
EDIT:
int duration = [videos valueForKey:#"duration"];
int minutes = duration / 60;
int seconds = duration % 60;
NSString *time = [NSString stringWithFormat:#"%d:%02d", minutes, seconds];
Assuming the duration value is really the duration in seconds, then you can calculate the number of minutes and seconds and then format those into a string.
int duration = ... // some duration from the JSON
int minutes = duration / 60;
int seconds = duration % 60;
NSString *time = [NSString stringWithFormat:#"%d:%02d", minutes, seconds];
You should use DateComponentsFormatter if the duration is intended to be user-facing:
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [ .minute, .second ]
formatter.zeroFormattingBehavior = [ .pad ]
let formattedDuration = formatter.string(from: duration)!
Try this very optimized
+ (NSString *)timeFormatConvertToSeconds:(NSString *)timeSecs
{
int totalSeconds=[timeSecs intValue];
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
return [NSString stringWithFormat:#"%02d:%02d:%02d",hours, minutes, seconds];
}
int sec = diff;//INFO: time in seconds
int a_sec = 1;
int a_min = a_sec * 60;
int an_hour = a_min * 60;
int a_day = an_hour * 24;
int a_month = a_day * 30;
int a_year = a_day * 365;
NSString *text = #"";
if (sec >= a_year)
{
int years = floor(sec / a_year);
text = [NSString stringWithFormat:#"%d year%# ", years, years > 0 ? #"s" : #""];
sec = sec - (years * a_year);
}
if (sec >= a_month)
{
int months = floor(sec / a_month);
text = [NSString stringWithFormat:#"%#%d month%# ", text, months, months > 0 ? #"s" : #""];
sec = sec - (months * a_month);
}
if (sec >= a_day)
{
int days = floor(sec / a_day);
text = [NSString stringWithFormat:#"%#%d day%# ", text, days, days > 0 ? #"s" : #""];
sec = sec - (days * a_day);
}
if (sec >= an_hour)
{
int hours = floor(sec / an_hour);
text = [NSString stringWithFormat:#"%#%d hour%# ", text, hours, hours > 0 ? #"s" : #""];
sec = sec - (hours * an_hour);
}
if (sec >= a_min)
{
int minutes = floor(sec / a_min);
text = [NSString stringWithFormat:#"%#%d minute%# ", text, minutes, minutes > 0 ? #"s" : #""];
sec = sec - (minutes * a_min);
}
if (sec >= a_sec)
{
int seconds = floor(sec / a_sec);
text = [NSString stringWithFormat:#"%#%d second%#", text, seconds, seconds > 0 ? #"s" : #""];
}
NSLog(#"<%#>", text);
Here is the great code I finds for this
int duration = 1221;
int minutes = floor(duration/60)
int seconds = round(duration - (minutes * 60))
NSString * timeStr = [NSString stringWithFormat:#"%i:%i",minutes,seconds];
NSLog(#"Dilip timeStr : %#",timeStr);
And the output will belike this
Dilip timeStr : 20:21
You can subString the 2321 and get the first string as 23 and the second as 21 and convert them to int. Also check for the length of the text:
if (text.length < 4)
//add zeros on the left of String until be of length 4
Objective C:
NSDateComponentsFormatter * formatter = [[NSDateComponentsFormatter alloc]init];
[formatter setUnitsStyle:NSDateComponentsFormatterUnitsStyleShort];
[formatter setAllowedUnits:NSCalendarUnitSecond | NSCalendarUnitMinute];
[formatter setZeroFormattingBehavior:NSDateComponentsFormatterZeroFormattingBehaviorPad];
return [formatter stringFromTimeInterval:duration];
I wanted to convert a date (nsdate) to tick values. Tick values are (1 Tick = 0.1 microseconds or 0.0001 milliseconds) since 1 Jan 0001 00:00:00 GMT. NSDate has functions like timeIntervalSince1970. So, how do I convert it?
I would like to share my experience:
I tried to find the seconds from 01/01/0001 and then multiply by 10,000,000. However, it gave me wrong results. So, I found out that 01/01/1970 is 621355968000000000 ticks from 01/01/0001 and used the following formula along with timeIntervalSince1970 function of NSDate.
Ticks = (MilliSeconds * 10000) + 621355968000000000
MilliSeconds = (Ticks - 621355968000000000) / 10000
Here is the outcome:
+(NSString *) dateToTicks:(NSDate *) date
{
NSString *conversionDateStr = [self dateToYYYYMMDDString:date];
NSDate *conversionDate = [self stringYYYYMMDDToDate:conversionDateStr];
NSLog(#"%#",[date description]);
NSLog(#"%#",[conversionDate description]);
double tickFactor = 10000000;
double timeSince1970 = [conversionDate timeIntervalSince1970];
double doubleValue = (timeSince1970 * tickFactor ) + 621355968000000000;
NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[numberFormatter setNumberStyle:NSNumberFormatterNoStyle];
NSNumber *nsNumber = [NSNumber numberWithDouble:doubleValue];
return [numberFormatter stringFromNumber:nsNumber];
}
Likewise, to convert from tick to date:
//MilliSeconds = (Ticks - 621355968000000000) / 10000
+(NSDate *) ticksToDate:(NSString *) ticks
{
double tickFactor = 10000000;
double ticksDoubleValue = [ticks doubleValue];
double seconds = ((ticksDoubleValue - 621355968000000000)/ tickFactor);
NSDate *returnDate = [NSDate dateWithTimeIntervalSince1970:seconds];
NSLog(#"%#",[returnDate description]);
return returnDate;
}