Utility library for, given a start and a end dates, obtain the elapsed time between the two dates in terms of years, months and days.
- 1 year, 1 month, 12 days
- 7 days
- 3 month, 19 days
- 1 year, 24 days
Gradle:
compile 'com.github.marlonlom:elapsed_time:$latestVersion'
Maven:
<dependency>
<groupId>com.github.marlonlom</groupId>
<artifactId>elapsed_time</artifactId>
<version>$latestVersion</version>
</dependency>
Use it passing two dates, a starting one and the ending one, for obtaining the duration elapsed between those, that contains info about days, months and years (in reverse order, lol).
Classes to keep in mind:
- TimeCount: Describes the elapsed time count (in terms of years,months,days) between two dates.
- ElapsedTimes: The Utility class.
/*
* Pass two dates, you can do so using java.util.Calendar or another class that
* handles java.util.Date objects, its required to use Date objects.
* in the snippet, its used the java.text.SimpleDateFormat for generate
* two dates using strings in the date format provided.
*/
val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
val startDate = sdf.parse("23/09/2015")
val endDate = sdf.parse("04/11/2016")
/* Given two dates, obtain the elapsed time between those dates. */
val elapsedTime = ElapsedTimes.from(startDate).to(endDate).compare()
println("$elapsedTime") // prints '1 year,1 month, 11 days'
You can pass the starting date as normal, when done, use the method 'toNow()' for comparing using the actual datetime as the end date.
val twoDaysBeforeNow = Calendar.getInstance().apply { add(Calendar.DATE, -2) }
val elapsedTime = ElapsedTimes.from(twoDaysBeforeNow.time).toNow().compare()
println("$elapsedTime") // prints '2 days'
When comparing a starting date that is after the ending date, the utility throws an java.lang.IllegalArgumentException.
When starting date is equal to the ending date, the utility returns zero years, zero months and zero days.
If you like this library, please tell others about it 👍👍
- Follow me on Twitter: @Marlonlom
- Contact me on LinkedIn: Marlonlom
Copyright 2020 marlonlom
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.