在android kotlin中显示基于所需输出格式的日期不起作用



我正在Android Kotlin中将UTC日期转换为本地时区日期。将UTC转换为本地时区运行良好。我需要输出格式日期的具体要求格式如下:

2020年6月12日

为此,我已经给出了所需的输出格式,但在转换后,它不会以我所需的特定格式显示。以下是我的代码:

实际上,根据我的要求,我们有一些默认的输入日期格式。。。我正在传递来自API的值的输入日期输入可以来自API的任何格式所以我维护了一个包含所有输入格式的枚举类为此,我添加了以下条件

val inputDate = "2020-09-23 7:38:00"

for (item in DateFormats.values()) {
try {
val date = SimpleDateFormat(item.pattern).parse(inputDate)
localDate = utcToLocalTimeZone(item.pattern,outputDateFormat,date.toString())
break
}
catch(e:ParseException)
{
e.printStackTrace()
}
}
so when I pass inputDate directly it is displaying the correct output format
but when I convert date.tostring and passing that as input it's not converting to the required output format

fun utcToLocalTimeZone(inputFormat : String,outputFormat : String,dateToConvert : String): String {
var dateToReturn = dateToConvert
val sdf = SimpleDateFormat(inputFormat)
sdf.timeZone = TimeZone.getTimeZone("UTC")
var gmt: Date? = null
val sdfOutputToSend =
SimpleDateFormat(outputFormat)
sdfOutputToSend.timeZone = TimeZone.getDefault()

try {
gmt = sdf.parse(dateToConvert)
dateToReturn = sdfOutputToSend.format(gmt)
} catch (e: ParseException) {
e.printStackTrace()
}
return dateToReturn
}

你能帮我做这个吗。非常感谢。

只需遵循此函数即可。

fun getTime(
originalString: String?,
givenFormat: String = "yyyy-MM-dd HH:mm:ss",
format: String
): String {
var str = ""
try {
val simpleDateFormat = SimpleDateFormat(givenFormat, Locale.getDefault())
val date = simpleDateFormat.parse(originalString ?: "")
str = SimpleDateFormat(format, Locale.getDefault()).format(
date.ifNotNullOrElse({ it },
{ "" })
)
} catch (e: ParseException) {
return ""
}
return str
}

ifNotNullOrElse获取给定value的所需值,无论其是否为空

用法:
any_kind_of_value.ifNotNullOrElse({your_return_value_if_given_value_is_not_null}{your_return_value_if_given_value_is_null}(

现在您可以调用以下函数:

getTime(date.toString, givenFormat, format)

对于EX:

给定格式:"yyyy-MM-dd HH:mm:ss"

格式:"MMM dd, yyyy"

日期:2020-09-26 11:23:40

输出:Sep 26, 2020

最新更新