gpt4 book ai didi

java - 将日期字符串转换为整数数组

转载 作者:行者123 更新时间:2023-12-03 23:02:33 27 4
gpt4 key购买 nike

我有一个格式为“YYYY-MM-DD”的字符串,我想将其转换为整数数组

这是我的代码:

int year, month, day;
Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String strDate = dateFormat.format(date);

例如,如果日期是 2017-03-16,我希望我的数组像 [2017,3,16]。

最佳答案

首先我会说使用 LocalDate , DateTimeFormatter来自java-time API并停止使用CalendarSimpleDateFormat遗留日期类

LocalDate currentDate = LocalDate.now();
String dateString = currentDate.format(DateTimeFormatter.ISO_DATE);

如果要将日期字符串转换为int数组,则根据-进行分割。

Integer[] array = 
Arrays
.stream( dateString.split("-") )
.map( Integer::valueOf )
.toArray( Integer[]::new )
;

关于java - 将日期字符串转换为整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60698332/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com