Authors Top

If you have a few years of experience with the Kotlin language and server-side development, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

1. Overview

Dealing with dates in software development concerns a wide variety of tasks to solve specific problems. One regular task related to this is to get the current date or date/time.

In this tutorial, we’ll explore some techniques to get the current date/time in Kotlin.

2. Implementation

To handle date or date/time values, we’ll take advantage of the support that the LocalDate and LocalDateTime classes provide natively.

2.1. Current LocalDate and LocalDateTime

First, let’s use the static method now() to get the current date:

val current = LocalDate.now()

Similarly, let’s apply the same method to get the current date/time:

val current = LocalDateTime.now()

If we want to get the date in a certain format, we can apply the formatting with the help of the DateTimeFormatter class:

val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
val current = LocalDateTime.now().format(formatter)

2.2. Using Calendar

The Calendar class provides another approach to getting the current date/time by retrieving the time attribute. Additionally, we can apply the formatting to get a more suitable representation:

val time = Calendar.getInstance().time 
val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm") 
val current = formatter.format(time)

Furthermore, the Calendar class allows us to build the current date/time from its components:

val calendar = Calendar.getInstance()

val current = LocalDateTime.of(
	 calendar.get(Calendar.YEAR),
	 calendar.get(Calendar.MONTH),
	 calendar.get(Calendar.DAY_OF_MONTH),
	 calendar.get(Calendar.HOUR_OF_DAY),
	 calendar.get(Calendar.MINUTE),
	 calendar.get(Calendar.SECOND)
)

2.3. Using java.util.Date

The java.util package contains the Date class, which was used widely before the introduction of the java.time package. To get the current date using the java.util implementation, we simply need to instantiate a new object of the Date class. Additionally, we can apply a format in the same way we used before with DateTimeFormatter:

val formatter = SimpleDateFormat("yyyy-MM-dd")
val date = Date()
val current = formatter.format(date)

3. Conclusion

In this tutorial, we’ve explored some techniques to generate the current date/time in Kotlin. We saw the implementations using LocalDate, LocalDateTime, and Calendar, and also learned about the support provided by the java.util.Date class.

As always, the complete code for this article is available over on GitHub.

Authors Bottom

If you have a few years of experience with the Kotlin language and server-side development, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

Comments are closed on this article!