Some of these are quite trivial such as extracting the year, month or day from a
Date
:
var date = LocalDate.parse("2018-12-31")
assertThat(date.year).isEqualTo(2018)
assertThat(date.month).isEqualTo(Month.DECEMBER)
assertThat(date.dayOfMonth).isEqualTo(31)
We can also extract other information like e
ra
, d
ayOfTheWeek
or d
ayOfTheMonth
:
assertThat(date.era.toString()).isEqualTo("CE")
assertThat(date.dayOfWeek).isEqualTo(DayOfWeek.MONDAY)
assertThat(date.dayOfYear).isEqualTo(365)
5. Working With
Period
Finally, let’s look into working with
Periods
in Kotlin.
Periods represent a distance on the timeline. We can create a
Period
using
Period
‘s class factory method:
var period = Period.of(1, 2, 3)
This creates a
Period
of 1 year, 2 months and 3 days.
To add this
Period
to an existing date, we use the
LocalDate
‘s
plus()
method:
var date = LocalDate.of(2018, 6, 25)
var modifiedDate = date.plus(period)
This will add 1 year, 2 months and 3 days to the given date and produce the modified date:
assertThat(modifiedDate).isEqualTo("2019-08-28")
Similarly, we can subtract a
Period
from a given date:
var date = LocalDate.of(2018, 6, 25)
var modifiedDate = date.minus(period)
And as expected, the modified date will be:
assertThat(modifiedDate).isEqualTo("2017-04-22")
Also, we can use Periods to represent the distance between two dates.
Let’s suppose we have two dates, exactly 6 months apart from each other:
var date1 = LocalDate.parse("2018-06-25")
var date2 = LocalDate.parse("2018-12-25")
Now, we can represent the distance between these two dates using Period’s
between
method:
var period = Period.between(date1, date2)
The
period
variable will produce the following
:
assertThat(period.toString()).isEqualTo("P6M")
P
stands for
Period
and
6M
means 6 months.
6. Conclusion
In this article, we have learned the basics of how to work with Dates in Kotlin.
We have looked into how to create date instances using various methods and how to format date objects back into readable texts.
Furthermore, we looked into extracting components from
Date
objects and finally how to work with
Periods
in Kotlin.
The code used in this tutorial 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
.