【问题标题】:Convert string date like 20200917 iso date into readable date format android [duplicate]将字符串日期如20200917 iso日期转换为可读的日期格式android [重复]
【发布时间】:2020-09-24 08:28:33
【问题描述】:

我从 API 收到这种格式的日期:20200917。如何将其转换为日期?

【问题讨论】:

  • 到目前为止你尝试过什么?你能告诉我们你的尝试(在代码中)吗?您还可以指定您收到的 date 的类型。可能会猜到是String,但不能确定...
  • 它在字符串 20200917 中,即 2020-09-2017

标签: java android date kotlin


【解决方案1】:

我假设您收到了一个日期的 String 表示(不是 java.util.Date),您希望将其转换为不同的格式。

一种方法是String 操作,这不应该是第一选择。

另一种方法是使用过时的类java.util.Datejava.text.SimpleDateFormat 重新格式化该日期String(这已在另一个答案中显示)。但这不是我的选择,因为使用了旧的和麻烦的 API。

以下是使用 java.time 的方法(自 Java 8 起):

Java:

public static void main(String[] args) {
    // example input
    String input = "20200917";
    // parse the input String with a formatter that can handle the given format
    LocalDate localDate = LocalDate.parse(input, DateTimeFormatter.BASIC_ISO_DATE;
    /*
     * now that you have a LocalDate, you can use a custom or built-in formatter to
     * create a differently formatted String (built-in one used here)
     */
    String output = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
    // and then you can output the result
    System.out.println(String.format("%s ==> %s", input, output));
}

科特林:

fun main() {
    val input = "20200917"
    val localDate = LocalDate.parse(input, DateTimeFormatter.BASIC_ISO_DATE
    val output = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE)
    println("$input ==> $output")
}

每个sn-ps的输出

20200917 ==> 2020-09-17

【讨论】:

  • 感谢改进,代码相应调整
【解决方案2】:

编辑

您好,您可以这样做:

String trDate="20200917";    
Date tradeDate = new SimpleDateFormat("yyyyMMdd", 
Locale.ENGLISH).parse(trDate);
String krwtrDate = new SimpleDateFormat("yyyy-MM-dd", 
Locale.ENGLISH).format(tradeDate);

【讨论】:

  • 我不知道它是什么,但它不是 unix 时间戳。转换为毫秒时给出 08/22/1970 @ 7:21pm (UTC) 和 02/21/2610 @ 9:50pm (UTC)。
  • @GregoryNowik 考虑我编辑的答案
  • 我认为,对于仅包含数字和连字符的输出,Locale 不是必需的。我真的认为应该使用java.time...
  • 我建议你不要使用SimpleDateFormatDate。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time APILocalDateDateTimeFormatter
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-28
  • 1970-01-01
  • 1970-01-01
  • 2015-04-27
相关资源
最近更新 更多