Skip to content

Instantly share code, notes, and snippets.

@sunify
Created October 8, 2019 07:17
Show Gist options
  • Save sunify/8697ebe2767328849bd39c331f179f6f to your computer and use it in GitHub Desktop.
Save sunify/8697ebe2767328849bd39c331f179f6f to your computer and use it in GitHub Desktop.
function calcTimeParts(time) {
const digits = (time || '').replace(/[^0-9]/g, '').slice(0, 4).split('');
if (digits.length === 4) {
return [digits.slice(0, 2).join(''), digits.slice(2).join('')];
}
if (digits.length === 3) {
if (digits[0] === '0') { // Скорее всего вводят что-то вроде 09:00
return [digits.slice(0, 2).join(''), digits.slice(2).join('')];
}
return [digits.slice(0, 1).join(''), digits.slice(1).join('')];
}
return [digits.join('')];
}
/**
* @param t string
* @param m number
* @return string
*/
function max(t, m) {
return Number(t) > m ? String(m) : t;
}
function formatTime(time) {
const [h, m] = calcTimeParts(time);
if (h && m) {
return [max(h, 23), max(m, 59)].join(':');
}
return h;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment