Sling Academy
Home/Kotlin/How to Add or Subtract Days, Months, and Years in Kotlin

How to Add or Subtract Days, Months, and Years in Kotlin

Last updated: December 04, 2024

Working with dates and times is a common task in many software applications. In Kotlin, using the Java DateTime API, you can easily add or subtract days, months, and years from a given date. In this article, we'll explore how to perform these operations in Kotlin using code examples to guide your understanding.

Prerequisites

Before we move on to the coding examples, ensure you have a basic setup for Kotlin development, either in your Integrated Development Environment (IDE) like IntelliJ IDEA or by using Kotlin online compilers. Additionally, familiarity with Kotlin's syntax will be beneficial.

Using the java.time Package

The java.time package provides comprehensive classes to manipulate date and time, which are LocalDate, LocalDateTime, and ZonedDateTime. Here, we will use LocalDate to demonstrate adding or subtracting days, months, and years.

Adding Days

You can add days to a LocalDate instance using the plusDays() method. Let's look at an example:


import java.time.LocalDate

fun main() {
    val today = LocalDate.now()
    val addedDays = today.plusDays(10)
    println("Today's date: $today")
    println("Date after adding 10 days: $addedDays")
}

In this example, we first obtain the current date, and then we add 10 days to it using plusDays().

Subtracting Days

Similarly, you can subtract days from a LocalDate instance using the minusDays() method:


import java.time.LocalDate

fun main() {
    val today = LocalDate.now()
    val subtractedDays = today.minusDays(5)
    println("Today's date: $today")
    println("Date after subtracting 5 days: $subtractedDays")
}

This example subtracts 5 days from the current date using minusDays().

Adding and Subtracting Months

Adding or subtracting months follows the same pattern as days. Use plusMonths() or minusMonths():


import java.time.LocalDate

fun main() {
    val today = LocalDate.now()
    val addedMonths = today.plusMonths(3)
    val subtractedMonths = today.minusMonths(2)
    println("Today's date: $today")
    println("Date after adding 3 months: $addedMonths")
    println("Date after subtracting 2 months: $subtractedMonths")
}

This code snippet first adds 3 months to the current date, then subtracts 2 months from it.

Adding and Subtracting Years

You can manipulate the year component using plusYears() and minusYears():


import java.time.LocalDate

fun main() {
    val today = LocalDate.now()
    val addedYears = today.plusYears(1)
    val subtractedYears = today.minusYears(1)
    println("Today's date: $today")
    println("Date after adding 1 year: $addedYears")
    println("Date after subtracting 1 year: $subtractedYears")
}

Here, 1 year is added and subtracted to illustrate how LocalDate handles year changes.

Conclusion

Kotlin, combined with Java's java.time package, provides robust support for date and time manipulations. By using extension functions like plusDays(), minusMonths(), etc., you can manage dates efficiently and write cleaner code. Understanding these methods can aid you in handling different scenarios, such as scheduling future events or validating timeframes, much more effectively.

Next Article: Calculating the Difference Between Two Dates in Kotlin

Previous Article: Converting Dates to Strings in Kotlin

Series: Working with date & time in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin