Kotlin .asTimeZone()
Published Jun 20, 2024
Contribute to Docs
The .asTimeZone() method in Kotlin converts a UtcOffset object to a time zone with a fixed offset(FixedOffsetTimeZone object). This function is part of the kotlinx.datetime library. It is particularly useful in scenarios where working with fixed time zones is required within applications that handle multiple time zones.
Syntax
fun UtcOffset.asTimeZone(): FixedOffsetTimeZone
UtcOffset: Represents the UTC offset for which the fixed-offset time zone is created.FixedOffsetTimeZone: The return type of the function, representing the fixed-offset time zone with the specified UTC offset.
Example
// Importing the kotlinx.datetime library, which provides a modern date and time API for Kotlin.import kotlinx.datetime.*fun main() {// Converting a UtcOffset to a fixed-offset TimeZone.val timeZone = UtcOffset(hours = 5, minutes = 25).asTimeZone()// Printing a header to indicate information about the converted time zone will follow.println("Converted Time Zone:")// Printing the ID (name/identifier) of the converted time zone.println(" ID: ${timeZone.id}")// Printing the offset of the converted time zone from UTC.println(" Offset: ${timeZone.offset}")}
The above example code block converts an UtcOffset to a FixedOffsetTimeZone using Kotlin’s kotlinx.datetime library, it sets the offset to 5 hours and 25 minutes and then prints the information about the converted time zone. It produces the following output:
Converted Time Zone:ID: +05:25Offset: +05:25
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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