i have some date in "yyyy-MM-dd HH:mm:ss.S" format and want to get just the month and date. How can i format it in kotlin?
CodePudding user response:
You need to convert date from one format to other format.
Try below code to convert date string one format to other format:
@Throws(ParseException::class)
fun convertDateInString(dateTime: String?, inputFormat: String?, outputFormat: String?): String? {
val sdf = SimpleDateFormat(inputFormat, Locale.US)
val date = sdf.parse(dateTime)
val simpleDateFormat = SimpleDateFormat(outputFormat, Locale.US)
return simpleDateFormat.format(date)
}
In Activity or Fragment class:
var date = "2022-01-10 10:00:00.2"
var convertDate = convertDateInString(date, "yyyy-MM-dd HH:mm:ss.S", "dd-MM")
CodePudding user response:
You shouldn't be using SimpleDateFormat
as it's outdated and troublesome
Use LocalDateTime
to format the date.
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S")
val dateTime: LocalDateTime = LocalDateTime.parse(date, formatter)
Use DateTimeFormatter
if you want your date in different format
val formatter2: DateTimeFormatter = DateTimeFormatter.ofPattern("dd MMM")
Log.e("Date 3 ", dateTime.format(formatter2))
Or if you want date and month values from the date object use dayOfMonth
and monthValue
Log.e("Date 3 ", "Date ${dateTime.dayOfMonth} , Month ${dateTime.monthValue}")
Note: LocalDateTime
only works in android 8 and above, to use it below android 8 enable desugaring
In your app module's build.gradle
, add coreLibraryDesugaringEnabled
compileOptions {
// Flag to enable support for the new language APIs
coreLibraryDesugaringEnabled true
// Sets Java compatibility to Java 8
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
dependencies {
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}