简体   繁体   English

使用 Hilt 注入 SimpleDateFormater

[英]Inject SimpleDateFormater Using Hilt

I am using SimpleDateFormat in my ViewModel to format some data.我在我的 ViewModel 中使用 SimpleDateFormat 来格式化一些数据。 As you can see this way is not flexible because I couldn't change my format pattern whenever I want.如您所见,这种方式并不灵活,因为我无法随时更改我的格式模式。 What should I do to improve this?我应该怎么做才能改善这一点?

class DateFormat @Inject constructor() : SimpleDateFormat("EEE, MMM dd", Locale.US) {

    fun convertUnixTimeToDate(unixTime: Long): String {
        return try {
            val date = Date(unixTime * 1000)
            this.format(date)
        } catch (e: NumberFormatException) {
            e.toString()
        }
    }
}
@HiltViewModel
class WeatherViewModel @Inject constructor(
    private val repository: WeatherRepository,
) : ViewModel() {
    @Inject
    lateinit var dateFormat: DateFormat

I change to use function extentions for this.为此,我更改为使用 function 扩展名。

const val DATE_PATTERN = "EEE, MMM dd"
private const val DAY_NAME_IN_WEEK_PATTERN = "EEE"

fun Long.toDateString(pattern: String): String {
    val sdf = SimpleDateFormat(pattern, Locale.getDefault())
    val date = Date(this * 1000)
    return sdf.format(date)
}

fun Long.toDayNameInWeek(dt: Long): String {
    return when {
        (this - dt) * 1000 < DateUtils.HOUR_IN_MILLIS -> "Today"
        (this - dt) * 1000 < DateUtils.DAY_IN_MILLIS * 2 -> "Tomorrow"
        else -> this.toDateString(DAY_NAME_IN_WEEK_PATTERN)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM