Convert String Date to Date in Android (Java/Kotlin) without having to deal with Call requires API level 26

Viewed 2068

First: I found a lot of solutions but none of them is working for my issue.

Issue: I want to convert a string date in the format of yyyy-MM-dd to an actaul date, I can do it with the following method that I created but the problem is its only compatible with API Level 26 and above, and my minimum support Level is 19.

    //string to date convert
    @RequiresApi(Build.VERSION_CODES.O)
    fun convertStringDate(dateString: String): LocalDate {
        val format = DateTimeFormatter.ISO_DATE
        val tmpDate = LocalDate.parse("2019-12-10", format)
        var parsedDate: LocalDate = tmpDate
        try {
            parsedDate = LocalDate.parse(dateString, format)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return parsedDate
    }

Question: How can I convert a string in the format yyyy-MM-dd to actual date, so that it is compatible with API Level 19 and above ?

Answer Found: Add desugring in your module level build.gradle file as

implementation coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:1.1.5")

and also enable

coreLibraryDesugaringEnabled true

in compiler options in the same file

3 Answers

below code will work irrespective of versions

public static String getDateFormatyyyyMMMddToyyyyMMdd(String string) {
    SimpleDateFormat inputSDF = new SimpleDateFormat("yyyy-MMM-dd", Locale.getDefault());
    SimpleDateFormat outputSDF = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    Date date = null;
    try {
        //here you get Date object from string 
        date = inputSDF.parse(string);
    } catch (ParseException e) {
        return string;
    }
    //after changing date format again you can change to string with changed format
    return outputSDF.format(date);
}

Try this,it will work no need to use any library

fun getStringToDate() {
    val dtStart = "2021-06-30"
    val format = SimpleDateFormat("yyyy-MM-dd")

    val date = format.parse(dtStart)
    Log.e("date", "date: $date")
}
Related