One option is to convert it to a Long and back again, using your desired unit:

fun Duration.truncate(unit: DurationUnit): Duration =
    toLong(unit).toDuration(unit)
Answer from Sam on Stack Overflow
🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.math › truncate.html
truncate | Core API – Kotlin Programming Language
import kotlin.math.* import kotlin.test.* fun main() { //sampleStart println(floor(3.5)) // 3.0 println(ceil(3.5)) // 4.0 println(truncate(3.5)) // 3.0 println(round(3.5)) // 4.0 println(round(3.49)) // 3.0 println(floor(-3.5)) // -4.0 println(ceil(-3.5)) // -3.0 println(truncate(-3.5)) // -3.0 println(round(-3.5)) // -4.0 println(round(-3.49)) // -3.0 //sampleEnd }
🌐
Codecademy
codecademy.com › docs › kotlin › math methods › truncate()
Kotlin | Math Methods | truncate() | Codecademy
May 15, 2024 - The truncate() method rounds a Double or Float argument to the next whole value towards zero. If the value is positive, it will be rounded down towards zero.
🌐
W3cubDocs
docs.w3cub.com › kotlin › api › latest › jvm › stdlib › kotlin.math › truncate
kotlin.math.truncate - Kotlin - W3cubDocs
kotlin-stdlib / kotlin.math / truncate · Platform and version requirements: JVM (1.2), JS (1.2), Native (1.2) fun truncate(x: Double): Double · fun truncate(x: Float): Float · Rounds the given value x to an integer towards zero. Return · the value x having its fractional part truncated.
Top answer
1 of 2
7

One option is to convert it to a Long and back again, using your desired unit:

fun Duration.truncate(unit: DurationUnit): Duration =
    toLong(unit).toDuration(unit)
2 of 2
1

Here is a pure-Kotlin truncation function.

It uses Duration.toComponents() to get the constituent components of the duration. It then converts each back into a Duration, depending on whether it is equal to or larger than the requested DurationUnit.

import kotlin.time.*
import kotlin.time.DurationUnit.*
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.microseconds
import kotlin.time.Duration.Companion.nanoseconds
import kotlin.time.Duration.Companion.seconds

/**
 * Truncates the duration to the specified [unit].
 *
 * Truncating the duration removes any time units smaller than the specified unit
 * and returns a new [Duration] with the truncated value.
 *
 * @param unit The duration unit to truncate to.
 * @returns a new [Duration] truncated to the specified [unit].
 */
private fun Duration.truncate(unit: DurationUnit): Duration {
  return toComponents { days: Long, hours: Int, minutes: Int, seconds: Int, nanoseconds: Int ->
    when (unit) {
      NANOSECONDS  -> this // there's no smaller unit than NANOSECONDS, so just return the current Duration
      MICROSECONDS -> days.days + hours.hours + minutes.minutes + seconds.seconds + nanoseconds.nanoseconds.inWholeMicroseconds.microseconds
      MILLISECONDS -> days.days + hours.hours + minutes.minutes + seconds.seconds + nanoseconds.nanoseconds.inWholeMilliseconds.milliseconds
      SECONDS      -> days.days + hours.hours + minutes.minutes + seconds.seconds
      MINUTES      -> days.days + hours.hours + minutes.minutes
      HOURS        -> days.days + hours.hours
      DAYS         -> days.days
    }
  }
}

Notes:

  • nanoseconds is documented as being less than 1_000_000_000 (1 second), so there's no need to convert it to seconds.
  • In order to round the nanoseconds to microseconds the nanoseconds value is first converted to a duration (nanoseconds.nanoseconds), then rounded to microseconds (inWholeMicroseconds) and then converted to a duration (.microseconds). The same process is used to round nanoseconds to milliseconds.

Example

Here's an example usage demonstrates the truncate() function applied to a duration using different time units. Each truncation removes all time units smaller than the specified unit.

import kotlin.time.*
import kotlin.time.DurationUnit.*
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.microseconds
import kotlin.time.Duration.Companion.nanoseconds
import kotlin.time.Duration.Companion.seconds

fun main() {
  // create a duration
  val duration = 1.hours + 30.minutes + 45.seconds + 2.milliseconds + 3.microseconds + 5.nanoseconds
  println(duration)                        // 1h 30m 45.002003005s
  println(duration.truncate(NANOSECONDS))  // 1h 30m 45.002003005s (no truncation - can't go smaller than the smallest unit)
  println(duration.truncate(MICROSECONDS)) // 1h 30m 45.002003s    (no nanoseconds)
  println(duration.truncate(MILLISECONDS)) // 1h 30m 45.002s       (no milliseconds or nanoseconds)
  println(duration.truncate(SECONDS))      // 1h 30m 45s     (milliseconds and smaller are truncated)
  println(duration.truncate(MINUTES))      // 1h 30m         (seconds and smaller are truncated)
  println(duration.truncate(HOURS))        // 1h             (minutes and smaller are truncated)
  println(duration.truncate(DAYS))         // 0s             (all units are zeroed)
}
1h 30m 45.002003005s
1h 30m 45.002003005s
1h 30m 45.002003s
1h 30m 45.002s
1h 30m 45s
1h 30m
1h
0s

Run in Kotlin Playground

🌐
Dormoshe
dormoshe.io › trending-news › my-way-of-truncating-strings-in-kotlin-3i0k-20814
How to truncate strings in Kotlin?
When we have large strings and when we don't want to show the full content of it, we'll have to use what's called String Truncation. Basically, let's say we have this string: Lorem ipsum dolor sit ...
Top answer
1 of 12
376
s = s.substring(0, Math.min(s.length(), 10));

Using Math.min like this avoids an exception in the case where the string is already shorter than 10.


Notes:

  1. The above does simple trimming. If you actually want to replace the last characters with three dots if the string is too long, use Apache Commons StringUtils.abbreviate; see @H6's solution. If you want to use the Unicode horizontal ellipsis character, see @Basil's solution.

  2. For typical implementations of String, s.substring(0, s.length()) will return s rather than allocating a new String.

  3. This may behave incorrectly1 if your String contains Unicode codepoints outside of the BMP; e.g. Emojis. For a (more complicated) solution that works correctly for all Unicode code-points, see @sibnick's solution.


1 - A Unicode codepoint that is not on plane 0 (the BMP) is represented as a "surrogate pair" (i.e. two char values) in the String. By ignoring this, we might trim the string to fewer than 10 code points, or (worse) truncate it in the middle of a surrogate pair. On the other hand, String.length() is not the correct measure for Unicode text length, so trimming based on that property may be the wrong thing to do.

2 of 12
173

StringUtils.abbreviate from Apache Commons Lang library could be your friend:

StringUtils.abbreviate("abcdefg", 6) = "abc..."
StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
StringUtils.abbreviate("abcdefg", 4) = "a..."

Commons Lang3 even allow to set a custom String as replacement marker. With this you can for example set a single character ellipsis.

StringUtils.abbreviate("abcdefg", "\u2026", 6) = "abcde…"
Find elsewhere
🌐
Runebook.dev
runebook.dev › en › docs › kotlin › api › latest › jvm › stdlib › kotlin.math › truncate
kotlin.math.truncate English
kotlin-stdlib / kotlin.math / truncate · Platform and version requirements: JVM (1.2), JS (1.2), Native (1.2) fun truncate(x: Double): Double · fun truncate(x: Float): Float · Rounds the given value x to an integer towards zero. Return · the value x having its fractional part truncated.
🌐
JetBrains
youtrack.jetbrains.com › issue › KT-60217 › Kotlin-stdlib-add-Duration.truncate-utility-function
Kotlin stdlib: add `Duration.truncate()` utility function
{{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong
🌐
Techie Delight
techiedelight.com › home › kotlin › truncate a file in kotlin
Truncate a File in Kotlin | Techie Delight
March 12, 2022 - This post will discuss how to truncate a file to size zero in Kotlin... The recommended solution is to create a PrintWriter instance, which results in the specified file being truncated to size zero.
🌐
Medium
ajaydeepak.medium.com › kotlin-string-split-trim-substring-fad3bbb37649
Kotlin: String split, trim, substring | by Ajay Deepak | Medium
June 13, 2020 - Kotlin: String split, trim, substring If you are certain that the number is always at the start, then use split() with space as delimiter and from the returned list take the 1st item and parse it to …
🌐
GitHub
github.com › Kotlin › kotlinx-datetime › issues › 225
Feature Request: truncateTo for LocalTime · Issue #225 · Kotlin/kotlinx-datetime
August 31, 2022 - While this works, I'd much rather only have to add one more line, something like .truncateTo(DateTimeUnit.SECOND).
Author   Stephen-Hamilton-C
Top answer
1 of 2
17

According to the docs: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/trim.html

fun String.trim(): String Returns a string having leading and trailing whitespace removed.

The it <= ' ' would remove all the 'non printable' characters with ascii code less or equal than space (ascii decimal = 32) as carriage return, line feed...

I've just tested with many of this characters:

val kotlin = "\t\t"
println(kotlin)
   
val kotlin2 = "\t\t".trim()
println(kotlin2)
   
val kotlin3 = "\t\t".trim{it <= ' '}
println(kotlin3)

this outputs:

      


They both clean this characters. And as @AlexeyRomanov states kotlin understands as a whitespace character the ones that return true using the isWhitespace method. So the it <= ' ' is to make it only trim the same chars as java does and not the other whitespace characters according to the Unicode standard.

If we test for example the \u00A0 character:

val kotlin4 = "\u00A0\u00A0".trim()
println(kotlin4)
   
val kotlin5 = "\u00A0\u00A0".trim{it <= ' '}
println(kotlin5)

we can see the difference in output:


  

You can test it in the kotlin playground.

2 of 2
4

Java's trim documentation says

Otherwise, if there is no character with a code greater than '\u0020' in the string, then a String object representing an empty string is returned.

Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\u0020'. A String object is returned, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m + 1).

So the condition is exactly { it <= ' ' } (where it is a character in the string).

Kotlin instead uses

public fun CharSequence.trim(): CharSequence = trim(Char::isWhitespace)

which is true e.g. for non-breaking space \u00A0, Ogham space mark \u1680, etc. and false for some characters below ' ' (e.g. \u0001).

🌐
TutorialKart
tutorialkart.com › kotlin › how-to-trim-white-spaces-around-string-in-kotlin
How to Trim White Spaces around String in Kotlin?
May 9, 2023 - To trim white spaces around a string ... ends of this string. In the following example, we take a string in str, and trim the white spaces around it using trim() method....
🌐
Stonesoupprogramming
stonesoupprogramming.com › 2017 › 12 › 13 › kotlin-jdbc-create-insert-query-and-truncate-tables
Kotlin JDBC Create, Insert, Query, and Truncate Tables – Stone Soup Programming
December 11, 2017 - Kotlin works with JDK’s JDBC API. Once we obtain a connection to the database, we can get an instance of Statement. The Statement interface lets us work directly with the database and more importantly, allows us to send queries to the database. This post demonstrates how to use Statement to create a table, insert rows into it, query the table, and truncate it.