简体   繁体   中英

convert Date string to array of integers

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].

Firstly i would say to use LocalDate , DateTimeFormatter from java-time API and stop using Calendar 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 )
;

This makes sense if all of your dates were preformatted as described in your question. But if you are using date Objects I would take advantage of the Java 8+ capabilities.

First, define a lambda to extract the parts and return an array. Note that you can add other date components or easily change the order in the array.

        Function<LocalDate, int[]> getParts =
                ld -> new int[] { ld.getDayOfMonth(),
                        ld.getMonthValue(), ld.getYear() };

Then you can apply it like so.

        LocalDate d = LocalDate.of(2020, 3, 15);
        int[] parts = getParts.apply(d);
        System.out.println(Arrays.toString(parts));

Prints

[15, 3, 2020]

Or this

        // create a list of LocalDate objects.
        List<LocalDate> localDates = List.of(
        LocalDate.of(2020, 3, 15), LocalDate.of(2020, 3, 16));
        // and convert to a list of arrays of date attributes.
        List<int[]> dates = localDates.stream().map(getParts::apply)
                  .collect(Collectors.toList());
        dates.forEach(a->System.out.println(Arrays.toString(a)));

Prints

[15, 3, 2020]
[16, 3, 2020]

Another advantage of this is that you don't have to ensure the format is the same from date to date.

It's very quick and easy. If you are bound to use an array, the solution => import these=>

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;

then in your main or other method =>

    int[] dateArray = new int[100]; // or your desired size

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

    String[] line = strDate.split("-");

    for (int i = 0; i < line.length; i++)
    {
        dateArray[i] = Integer.parseInt(line[i]);
    }

should do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM