0

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

Abhi
  • 93
  • 1
  • 9
  • *I have tried every possible solution on stactoverflow but the exception occur while parsing the date string.* It should not (of course). Please show us the code you have tried and paste the exact exception message you are getting, and I am sure we can help you out. You may also link to the answers where you got that code from. – Ole V.V. Jul 12 '22 at 17:55
  • `Jul-07-2022 01:47 pm` looks a bit off standard to me. Unless you have very specific requirements, you should prefer giving your user Java’s built-in localized format. For example (in Java) `LocalDateTime.parse("2022-07-07T08:17:12.117000") .atOffset(ZoneOffset.UTC) .atZoneSameInstant(ZoneId.of("Asia/Kolkata")) .format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT).withLocale(Locale.forLanguageTag("en-IN")))` gives `07-Jul-2022, 1:47 pm`. It’s pretty close, isn’t it? – Ole V.V. Jul 12 '22 at 18:28
  • The bonus is that when you leave out the call to `withLocale()`, the user’s locale will be used, and audiences with different cultural backgrounds will all be happy. – Ole V.V. Jul 12 '22 at 18:31
  • More about parsing your string (without getting any exception) in [this answer](https://stackoverflow.com/a/67935390/5772882) and [this one](https://stackoverflow.com/a/54023929/5772882). – Ole V.V. Jul 12 '22 at 18:36

2 Answers2

2

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 match your specific string
    val dateTimePattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

    val formatter = DateTimeFormatter.ofPattern(dateTimePattern).withZone(
        ZoneOffset.UTC
    )
    val timeFormatter = DateTimeFormatter.ofPattern("hh: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"
}

This question is a more complete discussion around this topic for anyone interested.

Ionut
  • 678
  • 2
  • 19
-1

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.

Abhi
  • 93
  • 1
  • 9
  • 4
    Why don't you use `java.time`? Doesn't appear `@SuppressLint("SimpleDateFormat")` suspicious to you? It does to me, at least… – deHaar Jul 12 '22 at 06:12
  • 1
    Consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends. Use [desugaring](https://developer.android.com/studio/write/java8-support-table) in order to use [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). It is so much nicer to work with. – Ole V.V. Jul 12 '22 at 18:00