0

I am using SimpleDateFormat in my ViewModel to format some data. 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
Nero
  • 25
  • 7
  • Note that `SimpleDateFormat` is [not at all thread safe](https://stackoverflow.com/q/4021151/1676363), so you really, really should have separate instances if there's any even remote chance that you are using it on anything but a single, tightly controlled thread. – ianhanniballake Dec 28 '22 at 02:21
  • Thank you. Now I change my way at the answer. Seem today and tomorrow still string hardcode. Do you have any solution ? – Nero Dec 28 '22 at 02:52

1 Answers1

0

I change to use function extentions for this.

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(currentTimestamp: Long): String {
    return when {
        (this - currentTimestamp) * 1000 < DateUtils.HOUR_IN_MILLIS * 2 -> "Today"
        (this - currentTimestamp) * 1000 < DateUtils.DAY_IN_MILLIS * 2 -> "Tomorrow"
        else -> this.toDateString(DAY_NAME_IN_WEEK_PATTERN)
    }
}
Nero
  • 25
  • 7
  • The `Long` that you pass to `toDayNameInWeek`, does that represent time since epoch in seconds? – Arpit Shukla Dec 28 '22 at 03:23
  • Yes, it is unix time also. – Nero Dec 28 '22 at 09:55
  • Is your problem solved with this answer or are you still looking for a solution? – Arpit Shukla Dec 28 '22 at 17:14
  • Thanks, my problem solved now. By @ianhanniballake advice, I know I should use diffrent SimpleDateFormat instances when I need it. So this extension method is enough for me. – Nero Dec 29 '22 at 00:01
  • But "Today" and "Tomorrow" still hardcode strings, how I can improve it ? – Nero Dec 29 '22 at 00:02
  • You will have to hardcode it only. No built-in function will return Today and Tomorrow as output. Btw with your calculation, if current time is 11:30pm and the `dt` represents tomorrow's 12:15am. You code will show Today instead of Tomorrow. There are similar bugs in the Tomorrow logic. – Arpit Shukla Dec 29 '22 at 03:45
  • Due to the api so `this` (Long.) always bigger than the `dt` (means current time, the time when call api). I should change the name a littlbe bit. – Nero Dec 29 '22 at 05:28