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

问题描述

2021-07-06T19:27:46.811+0530 -> 字符串形式的当前值

我想转换为 05/07/2021,06:45 am 这种格式

提前致谢

解决方法

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

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

,

你可以这样做

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