Kotlin .toDateTimePeriod()

Anonymous contributor's avatar
Anonymous contributor
Published Nov 20, 2023
Contribute to Docs

The .toDateTimePeriod() method in Kotlin is a versatile function that transforms an ISO-8601 formatted string into a DateTimePeriod object. This conversion is particularly useful when working with durations, especially when expressing durations in terms of years, months, days, hours, minutes, seconds, and nanoseconds.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn Kotlin, the expressive, open-source programming language developed by JetBrains.
    • Beginner Friendly.
      9 hours

Syntax

isoString.toDateTimePeriod()
  • isoString: A string representing a length of time utilizing the ISO-8601 format (e.g., 1 day = P1D, 1 hour = PT1H).

Note: This method can also operate on Duration objects that are part of the kotlin.time library, but this is still experimental and many of the original methods have been deprecated.

Example

import kotlinx.datetime.*
fun main() {
val newPeriod = "P3DT12H".toDateTimePeriod()
val theDays = newPeriod.days
val theHours = newPeriod.hours
println("Total days in the period: $theDays")
println("Total hours in the period: $theHours")
}

The code above will output the following:

Total days in the period: 3
Total hours in the period: 12

Note: An IllegalArgumentException is raised if the total number of months in hours, minutes, seconds, and nanoseconds overflows a Long or if the string cannot be parsed.

All contributors

Contribute to Docs

Learn Kotlin on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn Kotlin, the expressive, open-source programming language developed by JetBrains.
    • Beginner Friendly.
      9 hours