2021-07-06T19:27:46.811+0530 -> Current value as string
I want to convert to 05/07/2021, 06:45 am this format
Thanks in advance
2021-07-06T19:27:46.811+0530 -> Current value as string
I want to convert to 05/07/2021, 06:45 am this format
Thanks in advance
Use java.time
:
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
fun main() {
val input = "2021-07-06T19:27:46.811+0530"
// define a DateTimeFormatter for parsing your input
val parser = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSx")
// and another one for formatting your output
val formatter = DateTimeFormatter.ofPattern("dd/MM/uuuu, hh:mm a")
// then parse the input to an OffsetDateTime using the parser
val converted: String = OffsetDateTime.parse(input, parser)
// and output the same time differently
.format(formatter)
// output the result
println(converted)
}
This code's output is
06/07/2021, 07:27 PM
Ok, it's not exactly the value as the example showing your desired output, but I think it's all about formatting here. Adjusting the values would require a little more effort including a brief description of the desired behaviour.
You can do it like this
Java:
SimpleDateFormat parserFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault());
SimpleDateFormat convertFormat = new SimpleDateFormat("dd/MM/yyyy, hh:mm a", Locale.getDefault());
Date date = null;
try {
date = parserFormat.parse("2021-07-06T19:27:46.811+0530");
if (date != null) {
String formatedDate = convertFormat.format(date);
Log.e("formatted date",formatedDate);
}
} catch (ParseException e) {
e.printStackTrace();
Log.e("formatted date",e.getMessage());
}
Kotlin:
val parserFormat =
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault())
val convertFormat =
SimpleDateFormat("dd/MM/yyyy, hh:mm a", Locale.getDefault())
var date: Date? = null
try {
date = parserFormat.parse("2021-07-06T19:27:46.811+0530")
if (date != null) {
val formatedDate = convertFormat.format(date)
Log.e("formatted date", formatedDate)
}
} catch (e: ParseException) {
e.printStackTrace()
Log.e("formatted date", e.message!!)
}
You can try this:
//Formats the date according to the given pattern
private fun dateFormat(date: Date, pattern: String = "yyyy-MM-dd"): String =
SimpleDateFormat(pattern, Locale.US).format(date)
And if you have to:
//string to date convert
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
}