1

I wanted that the program takes input removes the delimiters from that String then add it back then I can later parse it to a LocalDate object but I am not able to do the needful.

Scanner darshit = new Scanner(System.in);
String oo = "";
System.out.println("Enter your DOB: ");
String dob = darshit.next();
String[] words = dob.split("\\D");
for (int i = 0; i > words.length; i++) {
    oo = oo + words[i];
}
System.out.println(oo);

After entering the DOB as 25-06-2008, for example, the output should be 25062008 or 2662008 but instead of this, I get a blank line!

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Darshit ff
  • 39
  • 4

4 Answers4

7

Use DateTimeFormatter to parse the input string to LocalDate and then format the LocalDate into a String of the desired format.

Demo:

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

public class Main {
    public static void main(String[] args) {
        Scanner darshit = new Scanner(System.in);
        System.out.print("Enter your DOB: ");
        String dob = darshit.next();
        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("dd[-][/]MM[-][/]uuuu", Locale.ENGLISH);

        LocalDate date = LocalDate.parse(dob, dtfInput);
        // Output in the default format i.e. LocalDate#toString implementation
        // System.out.println(date);

        // Output in a custom format
        DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("ddMMuuuu", Locale.ENGLISH);
        String formatted = dtfOutput.format(date);
        System.out.println(formatted);
    }
}

Notice the optional patterns in the square bracket which one of the great things about DateTimeFormatter.

A sample run:

Enter your DOB: 25-06-2008
25062008

Another sample run:

Enter your DOB: 25/06/2008
25062008

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


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • I can't use ```DateTimeFormatter``` because It is not fixed the the input from which I want to remove delimiters is dd-MM-uuuu , it can also be dd/MM/uuuu . So is there something for this ? – Darshit ff Sep 14 '21 at 12:37
  • @Darshitff - In that case, you should use `dd[-][/]MM[-][/]uuuu` as the pattern which will allow you to input 25-06-2008 or 25/06/2008. Feel free to comment in case of any further doubt/issue. – Arvind Kumar Avinash Sep 14 '21 at 13:54
1

String.replaceAll() and DateTimeFormatter

private static final DateTimeFormatter DATE_PARSER
        = DateTimeFormatter.ofPattern("[-]d-M-u[-]", Locale.ROOT);
private static final DateTimeFormatter DATE_FORMATTER
        = DateTimeFormatter.ofPattern("dd-MM-uuuu", Locale.ROOT);

public static void parseAndFormat(String input) {
    String adapted = input.replaceAll("\\W+", "-");
    System.out.println("Adapted input string: " + adapted);
    LocalDate date = LocalDate.parse(adapted, DATE_PARSER);
    String formatted = date.format(DATE_FORMATTER);
    System.out.println("Formatted:            " + formatted);
}

The above method parses your string:

    parseAndFormat("25-06-2008");

Output:

Adapted input string: 25-06-2008
Formatted:            25-06-2008

It’s very tolerant to which delimiters the users decides to use between the numbers, and also before or after them if any:

    parseAndFormat("$5///7  2008 ?");
Adapted input string: -5-7-2008-
Formatted:            05-07-2008

How it works: input.replaceAll("\\W+", "-") substitutes any run of non-word characters — everything but letters a through z and digits 0 through 9 — with a single hyphen. No one is interested in seeing the adapted input string, I am only printing it for you to understand the process better. The formatter I use for parsing accepts an optional hyphen first and last. The square brackets in the format pattern denote optional parts. It also accepts day and month in 1 or 2 digits and year in up to 9 digits. I use a separate formatter for formatting so I can control that day and month come in 2 digits and there are no hyphens before nor after.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

Can you just use Java Streams with the Collectors joining call ?

String value = Arrays.asList(dob.split("\\D")).stream().collect(Collectors.joining());
stackoverflow
  • 18,348
  • 50
  • 129
  • 196
  • While string bashing kind of works, it is not the best way. Consider the case where the user enter their DOB as 2008-05-07. Or 123456789. – Stephen C Sep 15 '21 at 03:18
-1

I myself found the solution

import java.util.Scanner;
import java.time.format.*;
import java.time.*;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter your DOB: ");
    String dateOfBirth = scanner.next();
    String dateOfBirth1 = dateOfBirth.replaceAll("\\s", "");
    String[] dateOfBirthArray = dateOfBirth1.split("[\\s\\-\\.\\'\\?\\,\\_\\@]+");
      int[] dateOfBirthArray1 = new int[dateOfBirthArray.length];
      for (int i = 0; i < dateOfBirthArray.length; i++){
        dateOfBirthArray1[i] = Integer.parseInt(dateOfBirthArray[i]);
      }
      int dayDateOfBirth = dateOfBirthArray1[0] , monthDateOfBirth = dateOfBirthArray1[1];
      int yearDateOfBirth = dateOfBirthArray1[2];
      LocalDate today = LocalDate.now();
      LocalDate birthday = LocalDate.of(yearDateOfBirth, monthDateOfBirth, dayDateOfBirth);
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
      String birthday1 = birthday.format(formatter);
  }
}

According to me it is the easiest way and the public editors can edit the post for making it more clear

Darshit ff
  • 39
  • 4
  • It’s a *very* complicated way. Please use a `DateTimeFormatter` instead. – Ole V.V. Sep 15 '21 at 02:50
  • That is the best way lol , Let me try ```DateTimeFormatter``` – Darshit ff Sep 15 '21 at 03:03
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 15 '21 at 04:20
  • Sorry but relying on other people to edit your answer into good shape is ... not on. Especially since the the approach your code takes is overly complicated. – Stephen C Sep 15 '21 at 05:49