android 我需要显示短月份名称

tyu7yeag  于 2023-01-24  发布在  Android
关注(0)|答案(1)|浏览(101)

private fun joinedDate(date: String): String {
    val a = LocalDateTime.parse(
        date,
        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX")
                         .withLocale(Locale.getDefault())
    )

    val date = "${a.month.toString().lowercase().replaceFirstChar { it.uppercase() }}, ${a.year}"
        
    return date
}

这是我的代码,我需要显示月份简称(例如,Jan 表示一月)

qjp7pelc

qjp7pelc1#

您可以构建和使用一个合适的DateTimeFormatter,它只打印简短的月份、逗号和年份...

val dtfOut = DateTimeFormatter.ofPattern(
                 "MMM, uuuu", Locale.ENGLISH
             )

...然后在方法LocalDateTime.format(DateTimeFormatter)中使用它。
如果对象实际上有一个 * month-of-year * 和一个 * year *,它将打印所需的结果。
如果你不知道偏移量的格式,可以使用DateTimeFormatterBuilder来构建一个最灵活的DateTimeFormatter来解析,否则就使用问题中的那个。
完整示例:

import java.util.Locale
import java.time.LocalDateTime
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatterBuilder

/* 
  define the output formatter
  (short month, year, English)
 */
val dtfOut = DateTimeFormatter.ofPattern("MMM, uuuu", Locale.ENGLISH)

/* 
   prepare a formatter that is able to parse many
   different offsets and no offset at all
 */
val dtfIn = DateTimeFormatterBuilder()
                .optionalStart()
                    .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                    .appendOffsetId()
                .optionalEnd()
                .appendOptional(
                    DateTimeFormatter.ofPattern(
                        "uuuu-MM-dd'T'HH:mm:ss.SSSX"
                    )
                )
                .appendOptional(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                .toFormatter(Locale.ENGLISH);

// conversion method
private fun joinedDate(date: String): String {
    // just parse, format and return
    return LocalDateTime.parse(date, dtfIn)
                        .format(dtfOut)
}

// try with some different input values
fun main() {
    val someDateTimes = listOf(
        "2022-10-18T21:43:10.111+00",
        "2022-10-18T21:43:10.111+0000",
        "2022-10-18T21:43:10.111+00:00",
        "2022-10-18T21:43:10.111Z",
        "2022-10-18T21:43:10.111"
    )
    
    someDateTimes.forEach { println("${joinedDate(it)} <-- $it") }
}

输出:

Oct, 2022 <-- 2022-10-18T21:43:10.111+00
Oct, 2022 <-- 2022-10-18T21:43:10.111+0000
Oct, 2022 <-- 2022-10-18T21:43:10.111+00:00
Oct, 2022 <-- 2022-10-18T21:43:10.111Z
Oct, 2022 <-- 2022-10-18T21:43:10.111

相关问题