Challenge Formatting the Date

In the Crime Data Class how would I cast the Data to a DateFormat Object and then use that object in the Fragment? I am using

    fun bind(crime: Crime) {
        this.crime = crime
        titleTextView.text = this.crime.title
//            Chapter 10 Challenge: Formatting the Date
            dateTextView.text = this.crime.date.getLongDateFormat()
            solvedImageView.visibility = if (crime.isSolved) {
                View.VISIBLE
            } else {
                View.GONE
            }
        }

And Note having any luck

@Gawitt try the following

dateTextView.text = DateFormat.format("EEEE, MMM dd, yyyy.", this.crime.date)

You call the static format method of the Date Format class specifically the version that takes 2 parameters:

1.) A CharSequence (i.e. the custom date format you want for example if you don’t send a greetings card to you mother on mother’s day and you want to report that crime the custom date format would be “Sunday, May 10, 2020.” so your character sequence is “EEEE, MMM dd, yyyy.” accordingly :sunglasses: !

2.) A Date object i.e. the date for the crime.

Don’t hesitate to look at the android developer docs thats how you get through most of the challenges and learn more stuff. Hope this helps.

1 Like

where exactly do i place this line of code? I would have thought it goes in the onBindViewHolder override, like so:

override fun onBindViewHolder(CrimeListViewHolder, position: Int){
val crime = crimes[position]
holder.apply{
dateTextView.text = DateFormat.format(“EEEE,MMM dd, yyyy.”, this.crime.date)
}

oh. got it. Apparently I was using java.util version of DateFormat and needed to use the android.text.DateFormat

1 Like

No worries. Also the binding was extracted to a helper function called bind.

Inside CrimeListFragment.kt

import android.text.format.DateFormat

fun bind(crime: Crime){
            this.crime = crime
            titleTextView.text = this.crime.title
            //DateFormat Challenge
            dateTextView.text = DateFormat.format("EEE dd MMM yyyy, hh:mm", this.crime.date)
            //image visibility
            solvedImageView.visibility = if (crime.isSolved) View.VISIBLE else View.GONE
        }

If someone is having trouble doing this in 2021, the new way to do it is using the SimpleDateFormat class. Like this:

dateTextView.text = SimpleDateFormat(“EEEE, MMM dd, yyyy.”, Locale.US).format(this.crime.date)

1 Like