0
\$\begingroup\$

I'm trying to load a date in the form of a string. As there is always 4 possible date formats (x.x.xxxx, x.xx.xxxx, xx.x.xxxx, xx.xx.xxxx (day month year)) I had to take this into account and it is especially hard with the strings length of 8 as it is either xx.x or x.xx.

So I came up with this:

public void setDate(String CompleteDate, boolean loadOrNew){
  Date = CompleteDate;
  if(loadOrNew){
    int totalLength = Date.length();
    String sday = null;
    String smonth = null;
    String syear = null;
    if(totalLength == 9){
      sday = String.valueOf(Date.toCharArray(), 0, 2);
      smonth = String.valueOf(Date.toCharArray(), 3, 2);
      syear = String.valueOf(Date.toCharArray(), 6, 4);
    }else if(totalLength == 8){
      sday = String.valueOf(Date.toCharArray(), 0, 2);
      if(sday.contains(".")){
        smonth = String.valueOf(Date.toCharArray(), 2, 2);
      }else{
        smonth = String.valueOf(Date.toCharArray(),3, 1);
      }
      syear = String.valueOf(Date.toCharArray(), 5, 3);
    }else if(totalLength == 7){
      sday = String.valueOf(Date.toCharArray(), 0, 1);
      smonth = String.valueOf(Date.toCharArray(), 2, 1);
      syear = String.valueOf(Date.toCharArray(), 4, 4);
    }else{
      Toast.makeText(c, "Critical date format error occurred. Error G205", Toast.LENGTH_LONG).show();
    }
    sday.replace(".", "");
    smonth.replace(".", "");
    syear.replace(".", "");
    this.day = Integer.parseInt(sday);
    this.year = Integer.parseInt(syear);
    this.month = Integer.parseInt(smonth);
  }
  date.setText("Date: " + CompleteDate);
}

However it isn't correct as I get NumberFormatException with "1."

This means I somewhere messed up and the removing of the "." doesn't work. So I need help improving this so it works.

NOTE:

Some of this is android-specific, e.g. the Toast class and TextView class, but everything else is in standard Java.

date and Date isn't the same. Date is the String, date is the TextView(android).

| improve this question | | | | |
\$\endgroup\$
0
\$\begingroup\$

The easiest way to do this is to use String.split to find out the different parts of the date. The following is pseudo-java but it should give you the idea.

String date = <YourDateStringHere>
String dateParts[] = date.split("\\.");
int day = dateParts[0].toInt();
int month = dateParts[1].toInt();
int year = dateParts[2].toInt();

Basically the idea is to split the string at each "." character and parse the data between each dot. You can also take different order formats (MM.DD.YYYY instead of DD.MM.YYYY) into account by just swapping some indices around. We use the sequence "\\." to match the single character "." because the split method wants a regexp pattern.

| improve this answer | | | | |
\$\endgroup\$