All Downloads are FREE. Search and download functionalities are using the official Maven repository.

walkmc.extensions.Durations.kt Maven / Gradle / Ivy

package walkmc.extensions

import kotlin.time.*

/**
 * Formats this duration in days, hours, minutes and seconds unit.
 *
 * This differs from [Duration.toString] because, this not contains the nanoseconds
 * and the seconds is formated as integer.
 */
fun Duration.format(): String {
	val isNegative = isNegative()
	return buildString {
		if (isNegative) append('-')
		absoluteValue.toComponents { days, hours, minutes, seconds, nanoseconds ->
			val hasDays = days != 0L
			val hasHours = hours != 0
			val hasMinutes = minutes != 0
			val hasSeconds = seconds != 0 || nanoseconds != 0
			var components = 0
			
			if (hasDays) {
				append(days).append('d')
				components++
			}
			
			if (hasHours || (hasDays && (hasMinutes || hasSeconds))) {
				if (components++ > 0) append(' ')
				append(hours).append('h')
			}
			
			if (hasMinutes || (hasSeconds && (hasHours || hasDays))) {
				if (components++ > 0) append(' ')
				append(minutes).append('m')
			}
			
			if (hasSeconds) {
				if (components++ > 0) append(' ')
				append(seconds).append('s')
			}
			
			if (isNegative && components > 1) insert(1, '(').append(')')
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy