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

标签 java string date

我有一个格式为“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/

相关文章:

c++ - VC++ : How to get the time and date of a file?

java - 将mock注入(inject)Spring容器中,无需xml进行测试

java - 为什么 SimpleDateFormat 会更改日期?

java - 通过 && 递归返回两个方法

c - 如何遍历指向指针的指针?

javascript - jQuery Datepicker 错误显示

java - 无法使用 apache poi 从 excel 中检测删除线数据

C# 将字符串转换为日期时间 (AM : PM)

javascript - 用 Greasemonkey 替换网站上的 javascript

javascript - 如何在 Spring 中正确创建 JavaScript 日期数组?