1
    String nDate;
    String dateTemp;
    int i;

    nDate = kb.nextLine();
    String[] temp = nDate.split("-");
    int numDate = Integer.parseInt(String.valueOf(temp));

im having issues with the (temp) part in the last line. If for example my input is "06-21-2020", what I want to happen is it becomes "06212020"

3
  • 7
    What you're trying to do is not splitting, it's replacing '-' with nothing. Use replaceAll instead. Commented Jun 28, 2021 at 14:24
  • 1
    I recommend you don’t use strings nor integers for your dates (just as you don’t use strings and integers for floating-point values and Booleans — I hope). Use LocalDate for a date (like you use int or long for an integer). See the answer by Arvind Kumar Avinash.
    – Anonymous
    Commented Jun 28, 2021 at 18:32
  • Also while you can get 6212020 as an integer value, you can’t from that value tell that there originally was a leading zero.
    – Anonymous
    Commented Jun 28, 2021 at 18:38

2 Answers 2

9

Use replace() instead of split(). To further explain, String.valueOf() does not take an array of Strings.

String temp = nDate.replace("-","");
int numDate Integer.parseInt(temp);
0
3

java.time

The answer by Phaelax z is spot-on for your specific requirement.

However, I recommend you parse the date string to LocalDate and format it as you wish.

You will get much more than the required conversion e.g. just think of finding the name of the day on 06-21-2020 or something like converting to some other format e.g. Sun 21 June 2020. All such requirements can be easily done using the in-built API as shown in the following demo:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String nDate = "06-21-2020";

        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("MM-dd-uuuu", Locale.ENGLISH);
        LocalDate date = LocalDate.parse(nDate, dtfInput);

        DateTimeFormatter dtfOutput1 = DateTimeFormatter.ofPattern("MMdduuuu", Locale.ENGLISH);
        DateTimeFormatter dtfOutput2 = DateTimeFormatter.ofPattern("dd/MM/uuuu", Locale.ENGLISH);
        DateTimeFormatter dtfOutput3 = DateTimeFormatter.ofPattern("EEE dd MMM uuuu", Locale.ENGLISH);
        System.out.println(dtfOutput1.format(date));
        System.out.println(dtfOutput2.format(date));
        System.out.println(dtfOutput3.format(date));
    }
}

Output:

06212020
21/06/2020
Sun 21 Jun 2020

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.