improvement: hide seconds (#675)

* feat: optional timer seconds
This commit is contained in:
Carlos Valente
2023-12-31 12:13:05 +01:00
committed by GitHub
parent a5d8b91f34
commit 9a4d659b04
29 changed files with 223 additions and 125 deletions
@@ -36,4 +36,14 @@ describe('formatTime()', () => {
const time = formatTime(ms, options, () => '12');
expect(time).toStrictEqual('01:00 PM');
});
it('handles negative times', () => {
const ms = 1 * 60 * 60 * 1000;
const options = {
showSeconds: false,
format: 'hh:mm:ss',
};
const time = formatTime(ms * -1, options, () => '24');
expect(time).toStrictEqual('-01:00');
});
});
+11 -2
View File
@@ -46,12 +46,21 @@ type FormatOptions = {
* @param {function} resolver
* @return {string}
*/
export const formatTime = (milliseconds: number | null, options?: FormatOptions, resolver = resolveTimeFormat) => {
export const formatTime = (
milliseconds: number | null,
options?: FormatOptions,
resolver = resolveTimeFormat,
): string => {
if (milliseconds === null) {
return '...';
}
const timeFormat = resolver();
const fallback = options?.showSeconds ? 'hh:mm:ss a' : 'hh:mm a';
const { showSeconds = false, format: formatString = fallback } = options || {};
return timeFormat === '12' ? formatFromMillis(milliseconds, formatString) : millisToString(milliseconds, showSeconds);
const isNegative = (milliseconds ?? 0) < 0;
const display =
timeFormat === '12'
? formatFromMillis(Math.abs(milliseconds), formatString)
: millisToString(Math.abs(milliseconds), showSeconds);
return `${isNegative ? '-' : ''}${display}`;
};