Kotlin LocalDateTime Tutorial šŸŽÆ

beginner
14 min

Kotlin LocalDateTime Tutorial šŸŽÆ

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! šŸŽ‰

Understanding LocalDateTime šŸ“

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.

kotlin
import java.time.LocalDateTime val currentTime: LocalDateTime = LocalDateTime.now()

šŸ’” Pro Tip: Always import the necessary packages at the beginning of your code.

Creating LocalDateTime šŸŽÆ

There are several ways to create a LocalDateTime object. Let's explore some of them.

Using now()

Creates a LocalDateTime object with the current date and time.

kotlin
val currentTime: LocalDateTime = LocalDateTime.now()

Using Constructors

With Year, Month, Day of Month, Hour, Minute, and Second

kotlin
val dateTime: LocalDateTime = LocalDateTime.of(2022, 12, 31, 23, 59, 59)

With Instant (Epoch Seconds)

Creates a LocalDateTime object from the number of seconds since the Unix Epoch.

kotlin
val epochTime: Long = 1648436400L // Unix Epoch timestamp for 2022-01-01T00:00:00Z val dateTime: LocalDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(epochTime), ZoneOffset.UTC)

Manipulating LocalDateTime šŸŽÆ

LocalDateTime provides various methods to manipulate date and time.

Adding and Subtracting Time šŸ’”

You can add or subtract years, months, days, hours, minutes, and seconds using plus() and minus() methods.

kotlin
val birthday: LocalDateTime = LocalDateTime.of(1990, 1, 1, 0, 0, 0) val age: LocalDateTime = birthday.plusYears(30)

Formatting LocalDateTime šŸ’”

You can format LocalDateTime using the format() method.

kotlin
val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss") val formattedDateTime: String = currentTime.format(formatter)

Quiz šŸ“

Quick Quiz
Question 1 of 1

What is the purpose of the LocalDateTime class in Kotlin?

Remember, practice makes perfect! Keep coding and exploring the world of Kotlin. Happy coding! šŸ¤–šŸ’»āœØ

Kotlin LocalDateTime Tutorial šŸŽÆ - Kotlin | CodeYourCraft | CodeYourCraft