📅  最后修改于: 2023-12-03 15:17:09.319000             🧑  作者: Mango
The DateTimeFormatter
class in Kotlin provides a mechanism to format and parse dates and times. It is used to format a date in a given format and also to parse a string and convert it into a date. In this article, we'll discuss how to use the DateTimeFormatter
class in Kotlin.
To format a date, you need to create an instance of the DateTimeFormatter
class with the desired format. Then, you can use the format
method to format the date. Here's an example:
import java.time.LocalDate
import java.time.format.DateTimeFormatter
fun main() {
val date = LocalDate.now()
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy")
val formattedDate = formatter.format(date)
println(formattedDate)
}
In this example, we create a LocalDate
object representing the current date. Then, we create an instance of the DateTimeFormatter
class with the pattern "dd/MM/yyyy" to format the date as "day/month/year". We use the format
method to format the date and store the result in the formattedDate
variable. Finally, we print the formatted date using println
.
The output of this program will be something like this:
12/06/2021
To parse a string into a date, you need to create an instance of the DateTimeFormatter
class with the same format as the string. Then, you can use the parse
method to parse the string into a date. Here's an example:
import java.time.LocalDate
import java.time.format.DateTimeFormatter
fun main() {
val dateString = "12/06/2021"
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy")
val parsedDate = LocalDate.parse(dateString, formatter)
println(parsedDate)
}
In this example, we create a string representing the date "12/06/2021". Then, we create an instance of the DateTimeFormatter
class with the pattern "dd/MM/yyyy" to parse the string into a date. We use the parse
method to parse the string and store the result in the parsedDate
variable. Finally, we print the parsed date using println
.
The output of this program will be something like this:
2021-06-12
In this article, we discussed how to use the DateTimeFormatter
class in Kotlin. We learned how to format a date using a given format and how to parse a string into a date using the same format. The DateTimeFormatter
class is very useful when working with dates and times in Kotlin, and it provides a lot of flexibility in terms of formatting and parsing.