How to get day/month when i have this string input 2021-07-14T00:00:00.000-0300 in kotlin?

Viewed 62

Someone can help me? I need to convert this date string "2021-07-14T00:00:00.000-0300" into this 14th/july in kotlin.

This is what i was trying to.

 private fun ajusteDeData(baseData: String): String{
    //Convert baseData into formatedDate ("14th / July")
    var input = "2021-07-14T00:00:00.000-0300"
    var output_formated = "14 / 07"
    /*
     * how to do this?
    */
    return output_formated
}

Anyone can help me? Thanks.

2 Answers

Create constants:

const val INPUT_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" // for 2021-07-14T00:00:00.000-0300
const val OUTPUT_DATE_FORMAT = "d'th' / MMMM" // for "14th / July"

Declare function:

private fun convertDateToFormat(
        dateToConvert: String,
        inputDateFormat: String = INPUT_DATE_FORMAT,
        outputDateFormat: String = OUTPUT_DATE_FORMAT
    ): String? {
        return try {
            // First parse your string date in order to get Date object
            val dateObject = SimpleDateFormat(inputDateFormat, Locale.US).parse(dateToConvert)
            // Next format Date object to String
            dateObject?.run { SimpleDateFormat(outputDateFormat, Locale.US).format(this) }
        } catch (e: ParseException) {
            null // Most likely that 'inputDateFormat' or|and 'outputDateFormat' format doesn't fit 'dateToConvert' you trying to convert
        }
    }

Then simply call your function whenever you need converted string date:

var dateToConvert = "2021-07-14T00:00:00.000-0300"
val convertedDate = convertDateToFormat(dateToConvert)

Note: It is possible that ParseException will be thrown in case you pass wrong date format, so return type of fun convertDateToFormat() is String? not String

Update: Added corrections to INPUT_DATE_FORMAT and OUTPUT_DATE_FORMAT so that both formats match your specific case for input: 2021-07-13T00:00:00.000-0300 and for output: 14th / July

String parts[] = input.replace("T", "-").split("-");

String output = parts[2] + "/" + parts[1];
Related