Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved relative date time formatting #3132

Merged
merged 1 commit into from
Feb 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ class VideosAdapter(
video.views.formatShort() + " " +
root.context.getString(R.string.views_placeholder) +
TextUtils.SEPARATOR + video.uploaded?.let {
DateUtils.getRelativeTimeSpanString(it)
TextUtils.formatRelativeDate(it)
}
video.duration?.let { thumbnailDuration.setFormattedDuration(it, video.isShort) }
channelImage.setOnClickListener {
Expand Down Expand Up @@ -174,7 +174,7 @@ class VideosAdapter(
video.views.formatShort() + " " +
root.context.getString(R.string.views_placeholder) +
TextUtils.SEPARATOR + video.uploaded?.let {
DateUtils.getRelativeTimeSpanString(it)
TextUtils.formatRelativeDate(it)
}

thumbnailDuration.text =
Expand Down
23 changes: 23 additions & 0 deletions app/src/main/java/com/github/libretube/util/TextUtils.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package com.github.libretube.util

import android.icu.text.RelativeDateTimeFormatter
import android.os.Build
import android.text.format.DateUtils
import java.time.Instant
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.*
Expand All @@ -19,6 +23,10 @@ object TextUtils {
*/
const val RESERVED_CHARS = "?:\"*|/\\<>\u0000"

private const val weekInMillis: Long = 604800016
private const val monthInMillis: Long = 2629800000
private const val yearInMillis: Long = 31557600000

/**
* Localize the date from a time string
* @param date The date to parse
Expand Down Expand Up @@ -51,4 +59,19 @@ object TextUtils {
}
}
}

fun formatRelativeDate(unixTime: Long): CharSequence {
val timeDiff = Instant.now().toEpochMilli() - unixTime
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && timeDiff > weekInMillis) {
val fmt = RelativeDateTimeFormatter.getInstance()
val (timeFormat, time) = when {
timeDiff >= yearInMillis -> RelativeDateTimeFormatter.RelativeUnit.YEARS to timeDiff / yearInMillis
timeDiff >= monthInMillis -> RelativeDateTimeFormatter.RelativeUnit.MONTHS to timeDiff / monthInMillis
else -> RelativeDateTimeFormatter.RelativeUnit.WEEKS to timeDiff / weekInMillis
}
fmt.format(time.toDouble(), RelativeDateTimeFormatter.Direction.LAST, timeFormat)
} else {
DateUtils.getRelativeTimeSpanString(unixTime)
}
}
}