Skip to content

Instantly share code, notes, and snippets.

@nadar71
Last active October 25, 2020 15:04
Show Gist options
  • Save nadar71/9703a8e32d2e89b5b45c255b4e6f9762 to your computer and use it in GitHub Desktop.
Save nadar71/9703a8e32d2e89b5b45c255b4e6f9762 to your computer and use it in GitHub Desktop.
* Take the Long milliseconds returned by the system and stored in Room, * and convert it to a nicely formatted string for display. * * EEEE - Display the long letter version of the weekday * MMM - Display the letter abbreviation of the nmotny * dd-yyyy - day in month and full year numerically * HH:mm - Hours and minutes in 24hr format
/**
* Take the Long milliseconds returned by the system and stored in Room,
* and convert it to a nicely formatted string for display.
*
* EEEE - Display the long letter version of the weekday
* MMM - Display the letter abbreviation of the nmotny
* dd-yyyy - day in month and full year numerically
* HH:mm - Hours and minutes in 24hr format
*/
@SuppressLint("SimpleDateFormat")
fun convertLongToDateString(systemTime: Long): String {
return SimpleDateFormat("EEEE MMM-dd-yyyy' Time: 'HH:mm")
.format(systemTime).toString()
}
/**
* Takes a list of SleepNights and converts and formats it into one string for display.
*
* For display in a TextView, we have to supply one string, and styles are per TextView, not
* applicable per word. So, we build a formatted string using HTML. This is handy, but we will
* learn a better way of displaying this data in a future lesson.
*
* @param nights - List of all SleepNights in the database.
* @param resources - Resources object for all the resources defined for our app.
*
* @return Spanned - An interface for text that has formatting attached to it.
* See: https://developer.android.com/reference/android/text/Spanned
*/
fun formatNights(nights: List<SleepNight>, resources: Resources): Spanned {
val sb = StringBuilder()
sb.apply {
append(resources.getString(R.string.title))
nights.forEach {
append("<br>")
append(resources.getString(R.string.start_time))
append("\t${convertLongToDateString(it.startTimeMilli)}<br>")
if (it.endTimeMilli != it.startTimeMilli) {
append(resources.getString(R.string.end_time))
append("\t${convertLongToDateString(it.endTimeMilli)}<br>")
append(resources.getString(R.string.quality))
append("\t${convertNumericQualityToString(it.sleepQuality, resources)}<br>")
append(resources.getString(R.string.hours_slept))
// Hours
append("\t ${it.endTimeMilli.minus(it.startTimeMilli) / 1000 / 60 / 60}:")
// Minutes
append("${it.endTimeMilli.minus(it.startTimeMilli) / 1000 / 60}:")
// Seconds
append("${it.endTimeMilli.minus(it.startTimeMilli) / 1000}<br><br>")
}
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return Html.fromHtml(sb.toString(), Html.FROM_HTML_MODE_LEGACY)
} else {
return HtmlCompat.fromHtml(sb.toString(), HtmlCompat.FROM_HTML_MODE_LEGACY)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment