Skip to content

Instantly share code, notes, and snippets.

@shekhar12020
Last active January 20, 2020 13:37
Show Gist options
  • Save shekhar12020/7099aca0be2c03e5e11e5b57c2de67ad to your computer and use it in GitHub Desktop.
Save shekhar12020/7099aca0be2c03e5e11e5b57c2de67ad to your computer and use it in GitHub Desktop.
Covert Time To Text (eg:- x min ago)
fun covertTimeToText() {
val dataDate = "2020-01-17T19:04:06.811Z"
val dateFormatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
val timezoneName = TimeZone.getDefault().displayName
dateFormatter.timeZone = TimeZone.getTimeZone(timezoneName)
val localDate = dateFormatter.parse(dataDate)
val dateFormatter2 = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
val finalDate = dateFormatter2.format(localDate)
println(finalDate)
var convTime: String? = null
val prefix = ""
val suffix = "Ago"
try {
val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
val pasTime = dateFormat.parse(finalDate)
val nowTime = Date()
val dateDiff = nowTime.time - pasTime.getTime()
val second = TimeUnit.MILLISECONDS.toSeconds(dateDiff)
val minute = TimeUnit.MILLISECONDS.toMinutes(dateDiff)
val hour = TimeUnit.MILLISECONDS.toHours(dateDiff)
val day = TimeUnit.MILLISECONDS.toDays(dateDiff)
when {
second < 60 -> convTime = "$second Seconds $suffix"
minute < 60 -> convTime = "$minute Minutes $suffix"
hour < 24 -> convTime = "$hour Hours $suffix"
day >= 7 -> convTime = when {
day > 360 -> (day / 360).toString() + " Years $suffix"
day > 30 -> (day / 30).toString() + " Months " + suffix
else -> (day / 7).toString() + " Week " + suffix
}
day < 7 -> convTime = "$day Days $suffix"
}
} catch (e: Exception) {
e.printStackTrace()
}
print(convTime ?: "")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment