cant subtract 2 timstamp long values

252 Views Asked by At

i'm trying to subtract two long(timestamp) but it kept crashing the application heres the code

//converting timestamp to actual time;
        val calendar = Calendar.getInstance(Locale.ENGLISH)
        calendar.timeInMillis = chat!!.timestamp!!.toLong()

        val t24 = 86400000 //24hrs in milliseconds
        val currentTime = System.currentTimeMillis().toInt()
        val chatTime: Int = chat.timestamp!!.toInt()
        val date = holder.date

        if ((currentTime - chatTime ) < t24 ) {
            val time =
                DateFormat.format("hh:mm aa", calendar).toString()
            date!!.text = time
        }else{

            val time =
                DateFormat.format("dd/MM//yyyy hh:mm aa", calendar).toString()
            date!!.text = time

        }

and this is the error

java.lang.NumberFormatException: For input string: "1594502477561"
        at java.lang.Integer.parseInt(Integer.java:618)
        at java.lang.Integer.parseInt(Integer.java:650)
        at com.google.meetchat.Adapters.ChatAdapter.onBindViewHolder(ChatAdapter.kt:64)
        at com.google.meetchat.Adapters.ChatAdapter.onBindViewHolder(ChatAdapter.kt:18)

line 64 is where chatTIme Variable is initialized

1

There are 1 best solutions below

0
Sergio On

You are using not-null assertion operator (!!) on some variables. It converts any value to a non-null type and throws an exception if the value is null.

I suspect you are getting NullPointerException when you use that operator on a variable. Please make sure that these variables are initialized before using operator !! on them:

chat, chat.timestamp, holder.date

UPDATE:

Please use Long for timestamps, don't convert them to Int. For example replace:

val currentTime = System.currentTimeMillis().toInt()
val chatTime: Int = chat.timestamp!!.toInt()

with:

val currentTime = System.currentTimeMillis()
val chatTime = chat.timestamp!!.toLong()

That's because timestamps are represented in milliseconds (or seconds if it is Unix timestamp) and the value can be higher than max value of Int type which is public const val MAX_VALUE: Int = 2147483647.