I have used the moment library to convert the date string in my local timezone in react but i have to implement the same in android but the problem is moment library is not available for java/kotlin.
I have tried every possible solution on stactoverflow but the exception occur while parsing the date string.
Format of the string is:
2022-07-07T08:17:12.117000
and want the output:
Jul-07-2022 01:47 pm
CodePudding user response:
In Kotlin, using the new Time
library this is how i would do it.
Also don't forget to change the pattern strings to match your specific case. In your case the string pattern should be val dateTimePattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
, but please check other approaches if it does not match.
fun formatDateTime(dateString: String): String {
//change this to mach your speciffic string
val dateTimePattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
val formatter = DateTimeFormatter.ofPattern(dateTimePattern).withZone(
ZoneOffset.UTC
)
val timeFormatter = DateTimeFormatter.ofPattern("KK:mm a")
val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
// \u00A0 is used to prevent the view from breaking line between "10:10" and "PM"
val dateTime =
ZonedDateTime.parse(dateString, formatter).withZoneSameInstant(ZoneId.systemDefault())
val eventDateString = dateTime.format(dateFormatter)
val formattedTime = dateTime.format(timeFormatter)
.replace(" ", "\u00A0")
return "$eventDateString $formattedTime"
}
CodePudding user response:
In JAVA
public String TimeConverter(String date) throws ParseException {
String dateStr = date;
try {
@SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(dateStr);
@SuppressLint("SimpleDateFormat") SimpleDateFormat dateformatter = new SimpleDateFormat("MMM-dd-yyyy hh:mm a");
dateformatter.setTimeZone(TimeZone.getDefault());
dateStr = dateformatter.format(value);
} catch (Exception e) {
dateStr = "00-00-0000 00:00";
}
return dateStr;
}
In Kotlin
fun main() {
var newdate = "2022-07-07T08:17:12.117000";
try {
val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
formatter.timeZone = TimeZone.getTimeZone("UTC")
val value = formatter.parse(newdate.toString())
val dateFormatter = SimpleDateFormat("MMM-dd-yyyy hh:mm a") //this format changeable
dateFormatter.timeZone = TimeZone.getDefault()
newdate = dateFormatter.format(value)
//Log.d("ourDate", ourDate);
} catch (e: Exception) {
newdate = "00-00-0000 00:00"
}
println(newdate)
}
May this help! I have been keep digging for this that's why i want to share so that it can help someone like me. Just remember to change the simple date format pattern according to your date pattern.