简体   繁体   English

不同格式的字符串到日期 kotlin

[英]different format String to date kotlin

i have response which contains the date in the string.我有响应,其中包含字符串中的日期。 the problem is that it has a different look in each item问题是它在每个项目中都有不同的外观

  {
                "date" : "1990-01-07
            }, {
                "date" : "01-07-1990
            }, {
                "date" : "01-07-2003
            }, {
                "date" : "1990-01-07"
            }

how to translate it into date formats in that case?在这种情况下如何将其转换为日期格式?

what i tried:我尝试了什么:

val birthday = taskDataBase?.birthday

val yearPattern = "dd-MM-yyyy"
birthday?.let {
    when (it != "") {
        true -> { SimpleDateFormat(yearPattern).parse(it) }
        false -> { "- -"
        }
    }
}

val ageData = when(birthday == null || birthday.isNullOrEmpty()){
    true -> "- -"
    false -> birthday
}

but it doesn't give any result.但它没有给出任何结果。 I need to get the date always of the same format, regardless of the format of the string tnx无论字符串 tnx 的格式如何,我都需要始终获取相同格式的日期

Looks like you have to just parse it twice in different formats:看起来你必须以不同的格式解析它两次:

val yearPattern1 = SimpleDateFormat("dd-MM-yyyy")
val yearPattern2 = SimpleDateFormat("yyyy-MM-dd")

val birthday = taskDataBase?.birthday
val birthdayDate = if (birthday.isNotEmpty()) {
    tryParse(birthday, yearPattern1) ?: tryParse(birthday, yearPattern2)
} else {
    null
}

...

fun tryParse(date: String, format: SimpleDateFormat): Date? = try {
    format.parse(date)
} catch (_: ParseException) {
    null
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM