Welcome to this comprehensive Kotlin LocalDateTime tutorial! This guide is designed to help both beginners and intermediates understand and master this powerful date and time handling library. Let's get started! š
LocalDateTime is a class in the Kotlin java.time package that represents a date and time without timezone information. It's useful for dealing with instantaneous points in time within a specific timezone.
import java.time.LocalDateTime
val currentTime: LocalDateTime = LocalDateTime.now()š” Pro Tip: Always import the necessary packages at the beginning of your code.
There are several ways to create a LocalDateTime object. Let's explore some of them.
now()Creates a LocalDateTime object with the current date and time.
val currentTime: LocalDateTime = LocalDateTime.now()val dateTime: LocalDateTime = LocalDateTime.of(2022, 12, 31, 23, 59, 59)Creates a LocalDateTime object from the number of seconds since the Unix Epoch.
val epochTime: Long = 1648436400L // Unix Epoch timestamp for 2022-01-01T00:00:00Z
val dateTime: LocalDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(epochTime), ZoneOffset.UTC)LocalDateTime provides various methods to manipulate date and time.
You can add or subtract years, months, days, hours, minutes, and seconds using plus() and minus() methods.
val birthday: LocalDateTime = LocalDateTime.of(1990, 1, 1, 0, 0, 0)
val age: LocalDateTime = birthday.plusYears(30)You can format LocalDateTime using the format() method.
val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss")
val formattedDateTime: String = currentTime.format(formatter)What is the purpose of the LocalDateTime class in Kotlin?
Remember, practice makes perfect! Keep coding and exploring the world of Kotlin. Happy coding! š¤š»āØ