English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn how to add two dates using Calendar in Kotlin.
Since the Java epoch is1970 years, which means, your date will be1970 years, when adding two date objects, the total will lose about1970 years. So, we use Calendar instead.
import java.util.Calendar fun main(args: Array<String>) { val c1 = Calendar.getInstance() val c2 = Calendar.getInstance() val cTotal = c1.clone() as Calendar cTotal.add(Calendar.YEAR, c2.get(Calendar.YEAR)) cTotal.add(Calendar.MONTH, c2.get(Calendar.MONTH) + 1) // Zero-based months cTotal.add(Calendar.DATE, c2.get(Calendar.DATE)) cTotal.add(Calendar.HOUR_OF_DAY, c2.get(Calendar.HOUR_OF_DAY)) cTotal.add(Calendar.MINUTE, c2.get(Calendar.MINUTE)) cTotal.add(Calendar.SECOND, c2.get(Calendar.SECOND)) cTotal.add(Calendar.MILLISECOND, c2.get(Calendar.MILLISECOND)) println("${c1.time} + ${c2.time} = ${cTotal.time}) }
When you run this program, the output is:
Tue Aug 08 10:20:56 NPT 2017 + Tue Aug 08 10:20:56 NPT 2017 = Mon Apr 16 20:41:53 NPT 4035
In the above program, c1and c2Store the current date. Then, we just need to clone c1and add c2of each DateTime property.
As you can see, we have added a month. This is because, in Kotlin, the month starts from 0.
Or, you can also use Joda for time in Kotlin/Date Operations.
The following is the equivalent Java code:Java Program to Add Two Dates.