如何将 2021-07-06T19:27:46.811+0530 格式转换为 d MMM yyyy, hh:mm aaa 这种格式 android

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 -> 当前值为字符串

我想转换成 05/07/2021,06:45 是这个格式

提前致谢

你可以这样做

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());
}

科特林:

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

你可以试试这个:

//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)

    

如果你必须:

//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
        }

使用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)
}

这段代码的输出是

06/07/2021, 07:27 PM

好的,这与显示您想要的输出的示例中的值不完全一样,但我认为这完全是关于格式化的。调整值需要更多的努力,包括对所需行为的简要描述。