Kotlin: Getting the difference betweeen two dates (now and previous date)

Viewed 7576

Sorry if similar questions have been asked too many times, but it seems that there's one or more issues with every answer I find.

I have a date in the form of a String: Ex.: "04112005"

This is a date. 4th of November, 2005.

I want to get the difference, in years and days, between the current date and this date.

The code I have so far gets the year and just substracts them:

fun getAlderFraFodselsdato(bDate: String): String {
    val bYr: Int = getBirthYearFromBirthDate(bDate)
    var cYr: Int = Integer.parseInt(SimpleDateFormat("yyyy").format(Date()))

    return (cYr-bYr).toString()
}

However, naturally, this is quite innacurate, since the month and days aren't included.

I've tried several approaches to create Date, LocalDate, SimpleDate etc. objects and using these to calcualate the difference. But for some reason I haven't gotten any of them to work.

I need to create a Date (or similar) object of the current year, month and day. Then I need to create the same object from a string containing say, month and year (""04112005""). Then I need to get the difference between these, in years, months and days.

All hints are appreciated.

3 Answers

I would use java.time.LocalDate for parsing and today along with a java.time.Period that calculates the period between two LocalDates for you.
See this example:

fun main(args: Array<String>) {
    // parse the date with a suitable formatter
    val from = LocalDate.parse("04112005", DateTimeFormatter.ofPattern("ddMMyyyy"))
    // get today's date
    val today = LocalDate.now()
    // calculate the period between those two
    var period = Period.between(from, today)
    // and print it in a human-readable way
    println("The difference between " + from.format(DateTimeFormatter.ISO_LOCAL_DATE)
            + " and " + today.format(DateTimeFormatter.ISO_LOCAL_DATE) + " is "
            + period.getYears() + " years, " + period.getMonths() + " months and "
            + period.getDays() + " days")
}

The output for a today of 2020-02-21 is

The difference between 2005-11-04 and 2020-02-21 is 14 years, 3 months and 17 days

It Works Below 26 API level There are too many formates of dates you just enter the format of date and required start date and end date. It will show you result. You just see different date formate hare and here if you need.

tvDifferenceDateResult.text = getDateDifference(
                "12 November, 2008",
                "31 August, 2021",
                "dd MMMM, yyyy")

General method to calculate date difference

fun getDateDifference(fromDate: String, toDate: String, formater: String):String{

        val fmt: DateTimeFormatter = DateTimeFormat.forPattern(formater)
        val mDate1: DateTime = fmt.parseDateTime(fromDate)
        val mDate2: DateTime = fmt.parseDateTime(toDate)
        val period = Period(mDate1, mDate2)
        // period give us Year, Month, Week and Days
        // days are between 0 to 6 
        // if you want to calculate days not weeks 
        //you just add 1 and multiply weeks by 7
        
        val mDays:Int = period.days + (period.weeks*7) + 1

        return "Year: ${period.years}\nMonth: ${period.months}\nDay: $mDays"
    }

For legacy Date functions below api 26 without running desugaring with Gradle plugin 4.0, java.time.* use:

fun getLegacyDateDifference(fromDate: String, toDate: String, formatter: String= "yyyy-MM-dd HH:mm:ss" , locale: Locale = Locale.getDefault()): Map<String, Long> {

    val fmt = SimpleDateFormat(formatter, locale)
    val bgn = fmt.parse(fromDate)
    val end = fmt.parse(toDate)
    
    val milliseconds = end.time - bgn.time
    val days = milliseconds / 1000 / 3600 / 24
    val hours = milliseconds / 1000 / 3600
    val minutes = milliseconds / 1000 / 3600
    val seconds = milliseconds / 1000
    val weeks = days.div(7)

    return mapOf("days" to days, "hours" to hours, "minutes" to minutes, "seconds" to seconds, "weeks" to weeks)
}

The above answers using java.time.* api is much cleaner and accurate though.

Related