Akshay Katariya
Akshay Katariya

Reputation: 338

Adding time to current time give error of 1 minute (Kotlin / Java)

When I add new time to calendar instance it gives me the error of 1 minute.

I get time from API response in this format

"PredictedArrivalDateTime": "/Date(1549309800000+1100)/"

this is just a dummy date from my API response

Then I use dateFromDotNetDate(dotNetDate: String) function to get difference in minutes.

After that, I want to add this minutes to the current time (eg: 12:30 ) and get new time which I am doing using the following function calculateNextTime(diffInMillies: Long)

Following is my DateTimeUtil util code

class DateTimeUtil {

    //Holds difference time difference in Minuets
    var mDifferenceMin: String? = null

    //HoldsETA of next Tram
    var mNextTime: String? = null

    //Convert .NET Date to Date
    fun dateFromDotNetDate(dotNetDate: String) {
        val startIndex = dotNetDate.indexOf("(") + 1
        val endIndex = dotNetDate.indexOf("+")
        val date = dotNetDate.substring(startIndex, endIndex)

        val unixTime = java.lang.Long.parseLong(date)
        val diffInMinutes = calculateDifference(Date(), unixTime)

        mDifferenceMin = diffInMinutes
        //----------------
        if (diffInMinutes == "0") {
            mDifferenceMin = "Now"
        } else
            mDifferenceMin = diffInMinutes
    }

    private fun calculateDifference(d1: Date, d2: Long): String? {
        val diffInMillies = Math.abs(d2 - d1.time)
        val diff = TimeUnit.MINUTES.convert(diffInMillies, TimeUnit.MILLISECONDS)

        calculateNextTime(diffInMillies)
        //----------------------
        return diff.toString()
    }

    private fun calculateNextTime(diffInMillies: Long) {
        //calculate next time
        val df = SimpleDateFormat("hh:mm aa", Locale.getDefault())
        val now = Calendar.getInstance()
        now.add(Calendar.MILLISECOND, diffInMillies.toInt())
        val teenMinutesFromNow = df.format(now.time)
        val nextTime = teenMinutesFromNow

        mNextTime = nextTime
    }
}

See Attached screensot

The current time is 12:41 in device, next ETA is 18 min so if i add (12:41 + 18 min = 12:59) but its showing 1:00

Upvotes: 1

Views: 3499

Answers (1)

Akshay Katariya
Akshay Katariya

Reputation: 338

I just change one line and magic happened

from

now.add(Calendar.MILLISECOND, diffInMillies.toInt())

to

now.add(Calendar.MINUTE, diffInMin.toInt())

As I thought the MILLISECOND calculation was introducing bugs in my function when I calculated using Minutes it's working fine

Upvotes: 1

Related Questions