toolbox icon indicating copy to clipboard operation
toolbox copied to clipboard

[Proposal]: format minutes into a nice time format

Open xGooddevilx opened this issue 1 year ago • 5 comments

Function Signature

const minuteFormat = (value) => {
	const minutes = Math.trunc(value / 60);
	const seconds = value % 60;

	return `${minutes < 10 ? `0${minutes}` : minutes}:${seconds < 10 ? `0${seconds}` : seconds}`;
};

Motivation

by using this helper function , we can easily format a minute number like 120 into " 02:00" time format. also it can be more customized and make it more reusable for any format we want by passing extra parameters

xGooddevilx avatar May 13 '24 10:05 xGooddevilx

Thanks @gooddevil79 for your contribution. I'd suggest extending the function to handle hours also.

function formatTime(seconds: number): string {}

formatTime(120);    // "02:00"
formatTime(3661);   // "01:01:01"

ASafaeirad avatar May 13 '24 11:05 ASafaeirad

Sure , I'll work on it

xGooddevilx avatar May 13 '24 11:05 xGooddevilx

const formatTime= (value , full=false) => {
  formatValue = (val) => (val < 10 ? `0${val}` : val);
  //A : 
  if(!value) return "00:00:00" ; 
  
  // B :
  if(!value){
   throw new Error("Forgot to pass the value")
  }
  
    const hours = Math.trunc(value / 3600);
    const remainingSeconds = value % 3600;
    const minutes = Math.trunc(remainingSeconds / 60);
    const seconds = remainingSeconds % 60;
    
    if(full||hours>0){
      return `${formatValue(hours)}:${formatValue(minutes)}:${formatValue(seconds)}`;
    }
    return `${formatValue(minutes)}:${formatValue(seconds)}`
};

formatTime(120); // 02:00
formatTime(120,true); // 00:02:00
formatTime(); // 00:00:00  ? Error

@ASafaeirad I came up with this aproach , but I think it could be better if we could pass percies option like

const options = { hours : true, minutes : true,seconds :true}

also which aproach is good for calling it with no arguments ? A or B

xGooddevilx avatar May 13 '24 12:05 xGooddevilx

What happens if we use { hours: true, minutes: false, seconds: true } 🤔

ASafaeirad avatar Jul 03 '24 10:07 ASafaeirad

I'd suggest this signature:

format(
  seconds: number,
  format: 'hh:mm:ss' | 'hh:mm' | 'mm:ss'
): string {}

ASafaeirad avatar Jul 03 '24 10:07 ASafaeirad