日期格式 [2020, 9, 15]:这是什么类型的格式?

huangapple go评论68阅读模式
英文:

Date Format [ 2020, 9, 15 ]: What type of format is this?

问题

我正在尝试解析外部的 JSON 数据,其中包含一些日期。日期的格式是:[ 2020, 9, 15 ]。我已经尝试将其作为字符串使用,但是没有成功。

你能告诉我这是什么样的日期格式吗?

英文:

I'm trying to consume external json, which has a few dates. Format for date is: [ 2020, 9, 15 ] I've tried using it as a string but it didn't work.

Can you please tell me what kind of format is this

答案1

得分: 3

java.time

将 JSON 数字数组读入 Java int[]int 数组),并从中构造一个 LocalDate

int[] arrayFromJson = { 2020, 9, 15 };
System.out.println("从 JSON 中获取的数组:" + Arrays.toString(arrayFromJson));

LocalDate date = LocalDate.of(arrayFromJson[0], arrayFromJson[1], arrayFromJson[2]);
System.out.println("作为 LocalDate 的日期:" + date);

输出结果:

>     从 JSON 中获取的数组:[2020, 9, 15]
>     作为 LocalDate 的日期:2020-09-15

LocalDate 是来自 java.time 的类,它是用于表示不带时间的日期的现代 Java 日期和时间 API,因此在这里使用该类是正确的选择。

读取和解析 JSON

如何将 JSON 读入 Java?这取决于您在其中使用的库。以下是使用 Jackson 的示例:

ObjectMapper mapper = new ObjectMapper();
String json = "[ 2020, 9, 15]";

int[] arrayFromJson = mapper.readValue(json, int[].class);
System.out.println(Arrays.toString(arrayFromJson));

输出结果:

>     [2020, 9, 15]
英文:

java.time

Read the JSON number array into a Java int[] (int array) and construct a LocalDate from it.

	int[] arrayFromJson = { 2020, 9, 15 };
	System.out.println("Array from JSON: " + Arrays.toString(arrayFromJson));
	
	LocalDate date = LocalDate.of(arrayFromJson[0], arrayFromJson[1], arrayFromJson[2]);
	System.out.println("Date as LocalDate: " + date);

Output is:

> Array from JSON: [2020, 9, 15]
> Date as LocalDate: 2020-09-15

LocalDate is the class from java.time, the modern Java date and time API, for representing a date without time of day, so the right class to use here.

Reading and parsing the JSON

How to read the JSON into Java? It depends on which library you are using for doing that. Here’s an example using Jackson:

    ObjectMapper mapper = new ObjectMapper();
    String json = "[ 2020, 9, 15]";

    int[] arrayFromJson = mapper.readValue(json, int[].class);
    System.out.println(Arrays.toString(arrayFromJson));

> [2020, 9, 15]

huangapple
  • 本文由 发表于 2020年9月22日 01:50:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63997546.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定