parseOrNull

Parses an ISO 8601 string that represents an instant (for example, 2020-08-30T18:43:00Z), or returns null if the string cannot be parsed or the boundaries of Instant are exceeded.

Guaranteed to parse all strings that Instant.toString produces.

Examples of instants in the ISO 8601 format:

  • 2020-08-30T18:43:00Z

  • 2020-08-30T18:43:00.50Z

  • 2020-08-30T18:43:00.123456789Z

  • 2020-08-30T18:40:00+03:00

  • 2020-08-30T18:40:00+03:30:20

  • 2020-01-01T23:59:59.123456789+01

  • +12020-01-31T23:59:59Z

See ISO-8601-1:2019, 5.4.2.1b), excluding the format without the offset.

The string is considered to represent time on the UTC-SLS time scale instead of UTC. In practice, this means that, even if there is a leap second on the given day, it will not affect how the time is parsed, even if it's in the last 1000 seconds of the day. Instead, even if there is a negative leap second on the given day, 23:59:59 is still considered a valid time. 23:59:60 is invalid on UTC-SLS, so parsing it will fail.

Since Kotlin

2.2

See also

for a version of this function that throws an exception on failure.

for formatting.

Samples

import kotlin.test.*
import kotlin.time.*
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.nanoseconds

fun main() { 
   //sampleStart 
   // Parsing a string that represents the Unix epoch.
val unixEpochInstant = Instant.parseOrNull("1970-01-01T00:00:00Z")
println(unixEpochInstant?.epochSeconds) // 0

// Parsing an ISO 8601 string with a time zone offset.
val instant = Instant.parseOrNull("2020-08-30T18:40:00+03:00")
// Instants are presented in the UTC time zone when converted to string.
println(instant.toString()) // 2020-08-30T15:40:00Z

// Failing to parse an invalid string returns null.
println(Instant.parseOrNull("Ten o'clock today")) // null
println(Instant.parseOrNull("2020-08-32T15:40:00Z")) // null
println(Instant.parseOrNull("+10000000000000-08-01T15:40:00Z")) // null 
   //sampleEnd
}