String format effective way

Hi

I am wondering if there is a more effective way of parsing a format string and replacing parts of the string with values. For example

"T: $H:$M:$S" should be replaced by hours, minutes seconds. But the string should be variable, it could only be $S or $M:$s or $H:$M .... (lowercase means no leading zero).

I tried to use Lang.format, but it doesn't really make it easier to replace the $M with $1$ etc, because the order is not fixed.

The way I am currently doing it, is going through the whole string and searching for the strings to replace (1 by 1).

var sec = Math.floor(val).toNumber();
var min = Math.floor(sec.toFloat()/60.0).toNumber();
var hr  = Math.floor(min.toFloat()/60.0).toNumber();
sec = sec%60;

for(var i = 0; i < fmttext.length(); i++) {
	var part = fmttext.substring(i, i+2);
	...
    if(part.equals("$H") || part.equals("$h")) {
		newtext += hr.format("%" + (part.equals("$H") ? "02" : "") + "d").toString();
		i++;
	} else {
		newtext += fmttext.substring(i, i+1);
	}
	...
}

The string.format function does not take any other characters as the one to replace, so that would make it much easier.

Thanks for any help!

regards

Erich

  • Instead of making this general purpos, why not make it a function where you pass a parameter as to what you want?

    In one of my functions, I do this, which might be another option:  Return mm:ss, if Hr is 0, or hh:mm:ss

    //
    	function toHMS(secs) {
        	var hr = secs/3600;
        	var min = (secs-(hr*3600))/60;
        	var sec = secs%60;
       		var ret=min.format("%02d")+":"+sec.format("%02d");
       		if(hr!=0) {ret=hr.format("%d")+":"+ret;}
       		return ret;
        }

  • I think I understand what you're getting at, and I think you can still solve this with String.format(). If you pass all of the possible tokens in the input parameters array, you can supply a different format string to get the various formats. Consider this

    var H = val / 3600;
    var M = val % 3600 / 60
    var S = val % 60;
    
    // $1$ is $H
    // $2$ is $M
    // $3$ is $S
    
    // if you want T: $H:$M:$S..
    fmt = "T: $1$:$2$:$3$";
    
    // if you want $S
    fmt = "T: $3$";
    
    // if you want $H:$M
    fmt = "T: $1$:$2$";
    
    var s = Lang.format(fmt, [ H, M, S ]);
    

    If you really must have strftime style formatting, feel free to have this code that I wrote a long time ago. It could probably be done more efficiently now with String.toUtf8Array and StringUtils.utf8ArrayToString, but that is an exercise for the reader...

    Sorry, I had to link to the file in my onedrive account because the forum software won't let me paste the source here.

    1drv.ms/.../s!Ak71bikqehCh2xsVUKbba9gREnuH

  • Hi

    Thanks for the code, I will take a look into that!

    regards

    Erich