In Kotlin, I'am trying to retrieve the SimpleDateFormat to a String variable but I receive Error. Any help please?
var someDate:SimpleDateFormat = SimpleDateFormat("2020-05-16")
var someText:String = someDate.toString() --> Error
In Kotlin, I'am trying to retrieve the SimpleDateFormat to a String variable but I receive Error. Any help please?
var someDate:SimpleDateFormat = SimpleDateFormat("2020-05-16")
var someText:String = someDate.toString() --> Error
Disclaimer: I do not need Kotlin syntax but AFAIK, Java code can be executed as it is in Kotlin or at least anyone working with Kotlin should be able to translate a Java code easily into Kotlin syntax.
The date-time API of java.util
and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API. Learn more about the modern date-time API at Trail: Date Time.
Note: If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Using the modern date-time API:
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2020, 5, 16);
String formatted = date.toString();
System.out.println(formatted);
}
}
Output:
2020-05-16
Note that LocalDate#toString
already returns the string in the ISO-8601 format, which is the format you want the output string in, and therefore you do need a formatter to get the string into the required format.
Using the legacy API:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2020);
// Note that in java.util date-time API, January is month, 0
calendar.set(Calendar.MONTH, 4);
calendar.set(Calendar.DAY_OF_MONTH, 16);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = calendar.getTime();
String formatted = sdf.format(date);
System.out.println(formatted);
}
}
Output:
2020-05-16
Kotlin API levels 26 or greater:
val parsedDate = LocalDateTime.parse("2018-12-14T09:55:00", DateTimeFormatter.ISO_DATE_TIME)
val formattedDate = parsedDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm"))
Below API levels 26:
val parser = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
val formatter = SimpleDateFormat("dd.MM.yyyy HH:mm")
val formattedDate = formatter.format(parser.parse("2018-12-14T09:55:00"))