将时间加到当前时间会产生1分钟的错误(Kotlin / Java)

时间:2019-02-04 19:40:37

标签: java android date datetime kotlin

当我向日历实例添加新时间时,它给了我1分钟的错误。

我以这种格式从API响应中获取时间

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

  

这只是我的API响应中的一个虚拟日期

然后我使用dateFromDotNetDate(dotNetDate: String)函数在几分钟内获得差异。

在那之后,我想将此分钟添加到当前时间(例如:12:30)并使用以下功能获取我正在做的新时间 calculateNextTime(diffInMillies: Long)

以下是我的DateTimeUtil实用程序代码

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

设备中当前时间为12:41,下一个预计到达时间为18分钟,因此如果我加上(12:41 + 18分钟= 12:59),但显示为1:00

1 个答案:

答案 0 :(得分:1)

我只换了一行就发生了魔术

来自

file name

File Explorer

我以为MILLISECOND计算会在我的函数中引入错误 当我使用Minutes进行计算时,效果很好