【发布时间】:2020-09-24 08:28:33
【问题描述】:
我从 API 收到这种格式的日期:20200917。如何将其转换为日期?
【问题讨论】:
-
到目前为止你尝试过什么?你能告诉我们你的尝试(在代码中)吗?您还可以指定您收到的 date 的类型。可能会猜到是
String,但不能确定... -
它在字符串 20200917 中,即 2020-09-2017
我从 API 收到这种格式的日期:20200917。如何将其转换为日期?
【问题讨论】:
String,但不能确定...
我假设您收到了一个日期的 String 表示(不是 java.util.Date),您希望将其转换为不同的格式。
一种方法是String 操作,这不应该是第一选择。
另一种方法是使用过时的类java.util.Date 和java.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
【讨论】:
编辑
您好,您可以这样做:
String trDate="20200917";
Date tradeDate = new SimpleDateFormat("yyyyMMdd",
Locale.ENGLISH).parse(trDate);
String krwtrDate = new SimpleDateFormat("yyyy-MM-dd",
Locale.ENGLISH).format(tradeDate);
【讨论】:
Locale 不是必需的。我真的认为应该使用java.time...
SimpleDateFormat 和Date。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time API 的LocalDate 和DateTimeFormatter。