Issue
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.
Solution
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
Answered By - Bhniy Andrew
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.