英文:
Convert string date like 20200917 iso date into readable date format android
问题
我从API收到的日期格式是:20200917
。如何将其转换为日期?
英文:
I am receiving a date in this format from API: 20200917
. How can I convert this into a date?
答案1
得分: 1
我假设您正在接收一个表示日期的String
表示,而不是java.util.Date
,您想将其转换为不同的格式。
一种方法是进行String
操作,但这不应该是首选方法。
另一种方法是使用过时的类java.util.Date
和java.text.SimpleDateFormat
来重新格式化日期String
(这已经在另一个回答中展示过)。但由于使用了旧的且麻烦的API,这也不是我的选择。
以下是如何使用java.time
(自Java 8以来)来实现:
Java:
public static void main(String[] args) {
// 示例输入
String input = "20200917";
// 使用可以处理给定格式的格式化程序解析输入字符串
LocalDate localDate = LocalDate.parse(input, DateTimeFormatter.BASIC_ISO_DATE);
/*
* 现在您有了一个LocalDate,您可以使用自定义或内置的格式化程序来创建格式不同的字符串(此处使用内置的格式化程序)
*/
String output = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
// 然后您可以输出结果
System.out.println(String.format("%s ==> %s", input, output));
}
Kotlin:
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");
}
这些代码片段的输出为
20200917 ==> 2020-09-17
英文:
I assume you are receiving a String
representation of a date (not a java.util.Date
) which you want to convert to a different format.
One way would be a String
manipulation, which shouldn't be the first choice.
Another way would be to use the outdated classes java.util.Date
and java.text.SimpleDateFormat
to reformat that date String
(this is already shown in another answer). But this would neither be my choice due to the use of an old and troublesome API.
Here's how you can do it with java.time
(since 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));
}
Kotlin:
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")
}
The output of each of these snippets
20200917 ==> 2020-09-17
答案2
得分: 0
EDIT
你可以像这样做:
String trDate = "20200917";
Date tradeDate = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).parse(trDate);
String krwtrDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).format(tradeDate);
英文:
EDIT
Hi you can do like this:
String trDate="20200917";
Date tradeDate = new SimpleDateFormat("yyyyMMdd",
Locale.ENGLISH).parse(trDate);
String krwtrDate = new SimpleDateFormat("yyyy-MM-dd",
Locale.ENGLISH).format(tradeDate);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论