Time Formating

 Show and get timestamp:
binding.time.text = formattedTimestamp(item.timeStamp)
Here are Different types of time formatting:

Absolute Date (e.g., “23 May 2024”)

fun formatDate(timestampMillis: Long?): String {
val date = timestampMillis?.let { Date(it) } ?: return "Unknown"
val sdf = SimpleDateFormat("dd MMM yyyy", Locale.getDefault())
return sdf.format(date)
}

Date & Time (e.g., “23 May 2024, 10:45 AM”)

fun formatDateTime(timestampMillis: Long?): String {
val date = timestampMillis?.let { Date(it) } ?: return "Unknown"
val sdf = SimpleDateFormat("dd MMM yyyy, hh:mm a", Locale.getDefault())
return sdf.format(date)
}


Time Only (e.g., “10:45 AM”)

fun formatTime(timestampMillis: Long?): String {
val date = timestampMillis?.let { Date(it) } ?: return "Unknown"
val sdf = SimpleDateFormat("hh:mm a", Locale.getDefault())
return sdf.format(date)
}

Relative Time (e.g., “2 days ago”)

fun getRelativeTimeSpan(timestampMillis: Long?): String {
val time = timestampMillis ?: return "Just now"
return DateUtils.getRelativeTimeSpanString(
time,
System.currentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS
).toString()
}


Relative Time 2 (for long. e.g., “1 month ago”)


fun formattedTimestamp(timestampMillis: Long?): String {
val timeStamp = timestampMillis ?: return "Just now"
val currentTime = System.currentTimeMillis()
if (timeStamp <= 0 || timeStamp > currentTime) return "Just now"

val diff = currentTime - timeStamp

return when {
diff < 60_000 -> "Just now"
diff < 60 * 60_000 -> "${diff / 60_000} minutes ago"
diff < 24 * 60 * 60_000 -> "${diff / (60 * 60_000)} hours ago"
diff < 7 * 24 * 60 * 60_000 -> "${diff / (24 * 60 * 60_000)} days ago"
diff < 30L * 24 * 60 * 60_000 -> "${diff / (7 * 24 * 60 * 60_000)} weeks ago"
else -> "${diff / (30L * 24 * 60 * 60_000)} months ago"
}
}

ISO 8601 (e.g., “2024-05-23T10:45:00Z”)


fun formatIso8601(timestampMillis: Long?): String {
val date = timestampMillis?.let { Date(it) } ?: return "Unknown"
val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault())
sdf.timeZone = TimeZone.getTimeZone("UTC")
return sdf.format(date)
}

Custom Format (e.g., “Thursday, 23 May 2024”)

fun formatCustomDate(timestampMillis: Long?): String {
val date = timestampMillis?.let { Date(it) } ?: return "Unknown"
val sdf = SimpleDateFormat("EEEE, dd MMM yyyy", Locale.getDefault())
return sdf.format(date)
}

Short Date (e.g., “23/05/24”)

fun formatShortDate(timestampMillis: Long?): String {
val date = timestampMillis?.let { Date(it) } ?: return "Unknown"
val sdf = SimpleDateFormat("dd/MM/yy", Locale.getDefault())
return sdf.format(date)
}




No comments:

Post a Comment