Skip to content

Instantly share code, notes, and snippets.

@iRYO400
Created July 17, 2018 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iRYO400/3a452a69b8afae8647e9582b688b84c6 to your computer and use it in GitHub Desktop.
Save iRYO400/3a452a69b8afae8647e9582b688b84c6 to your computer and use it in GitHub Desktop.
A-snippet #2 - Relative time converting
const val TIMESTAMP_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" // eg. 2018-04-01T04:20:25.434Z
/**
* Time converting from any timestamp pattern to "5 minutes ago", "1 day ago", etc.
*/
fun convertTime(timestamp: String): String {
val mDataFormat: DateFormat = SimpleDateFormat(TIMESTAMP_PATTERN, Locale.ENGLISH)
return try {
val date = mDataFormat.parse(timestamp)
val relativeDateStr = DateUtils.getRelativeTimeSpanString(date.time, Calendar.getInstance().timeInMillis, DateUtils.MINUTE_IN_MILLIS)
relativeDateStr.toString()
} catch (e: ParseException) {
Log.e("ParseException", "Unparseable date " + e.message)
timestamp
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment