Search code examples
androiddatetimekotlinsimpledateformat

How to convert 2021-07-06T19:27:46.811+0530 format to d MMM yyyy, hh:mm aaa this format in android


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


Solution

  • 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!!)
    }