androiduuidandroid-calendarunique-id

If you change the timeInMillis value of Calendar.getInstance() to int, can it be a unique id?


During Android app development, each item tries to attach a unique int type id. I thought that the point at which the item was created is unique, so after calling Calendar.getInstance(), I thought to give it by changing the value of timeInMillis to toInt(). Even if it is transformed into an int like this, does the value become unique?

Ex)

 val calendar = Calendar.getInstance()
 val longId = calendar.timeInMillis          // 1611807420557
 val intId = calendar.timeinMillis.toInt()   // 1194684557

As a result of my testing, the above values ​​were output. Is the 1194684557 value changed to int a unique id?


Solution

  • toInt() isn't a good idea because it won't work if your long is out of range of the int. I would recommend to divide the millis by something like 1000. And then convert it to int. Try something like that:

    val intId = (longId / 1000).toInt()