convert Date string to array of integers

bizzaro33 :

I have a string in the format: "YYYY-MM-DD" and I want to convert it into an array of integer

this is my code :

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

for example, if the date is 2017-03-16 I want my array be like [2017,3,16].

Deadpool :

Firstly i would say to use LocalDate, DateTimeFormatter from java-time API and stop usingCalendar and SimpleDateFormat legacy date class

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

If you want to convert date string to int array, then split is based on -.

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=415653&siteId=1