-1

so i get this string from a method:21\11\2016 and i need to split it at the backslashes. i tried to replace the single backslashes with some other characters but it doesn't work. the overall task i have to accomplish is to convert the String to a LocalDate. if anyone has an idea on how to do it please share it. i didn't find any working solution in here thats why i ask again

my approach:

    String datum=getComponentDateTextField().getText();
    // datum is "21\11\2016"
    datum=datum.replaceAll("\\\\", ".");
    String[] dates=datum.split(".");
    LocalDate dPresent = this.getDate();
    dPresent=dPresent.of(Integer.parseInt(dates[0]), Integer.parseInt(dates[1]), Integer.parseInt(dates[2]));
XtremeBaumer
  • 6,275
  • 3
  • 19
  • 65
  • 2
    If your string contains `/`, why do you try to replace ``\`` with dots? And then you try to split with any character but a linebreak char. If you want to split with `/`, just do so at the beginning. – Wiktor Stribiżew Nov 14 '16 at 13:27
  • dayum you right sir. i am dumb as hell right now xD can be closed now since the problem is answered – XtremeBaumer Nov 14 '16 at 13:30
  • anyways would you have an idea on how to split at single backslash? – XtremeBaumer Nov 14 '16 at 13:34
  • 1
    Splitting with a backslash is a [solved problem](http://stackoverflow.com/questions/23751618/how-to-split-a-java-string-at-backslash), `.split("\\\\")`. – Wiktor Stribiżew Nov 14 '16 at 13:39
  • only if its 2 backslashes. but what about 1? – XtremeBaumer Nov 14 '16 at 13:43
  • Refer to the linked question to split a String with a backslash. And since you appear to work with dates, it'd even be preferable to parse it directly, refer to http://stackoverflow.com/questions/4216745/java-string-to-date-conversion – Tunaki Nov 14 '16 at 14:35
  • the posted link only works if you have 2 backslashes... but what will you do if you only get 1 backslash? how will you split that? – XtremeBaumer Nov 14 '16 at 14:43

3 Answers3

2

Don't split. Just parse:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy\\MM\\dd");
LocalDate dPresent = LocalDate.parse(datum, formatter);
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

Use this method...

String date = "21/11/2016";

String[] splitedDataFrmDate = date.split("\\/");

for(String data:splitedDataFrmDate)

{

 System.out.println(data);

}
0

Call this method to covert string to Date instead of splitting with backslash and complicating.

Example:

java.util.Date result=Coverter.getDate("21/11/2016","dd/MM/yyyy");

    public static Date getDate(String dateStr, String mask) throws LinkedException {
            if (dateStr == null) {
                return null;
            }

            try {
                SimpleDateFormat format = new SimpleDateFormat(mask);
                return format.parse(dateStr);
            } catch (Exception e) {        
            }
        }
XtremeBaumer
  • 6,275
  • 3
  • 19
  • 65
Karthik
  • 545
  • 6
  • 23