Public method where a date is passed as a parameter, a parameter only

2

I need to create a public method called mostraData where a date is passed as a parameter (a parameter, not the separated day, month, and year), and the date is returned in the following format: dd / mm /aaaa .

Keep in mind that if values have fewer digits, you must fill in with leading zeros to fit the default format. I already created the builder as I was asked in the exercise (one per default and another per parameter) with the requested attributes as well. Thank you.

package fechaapp;

public class Fecha {
private int dia;
private int mes;
private int anyo;

public Fecha(){
    this.setDia(1);
    this.setMes(1);
    this.setAnyo(2000);
}

public Fecha(int dia, int mes, int anyo){
    this.setDia(dia);
    this.setMes(mes);
    this.setAnyo(anyo);
}

public int getDia() {
    return dia;
}

public void setDia(int dia) {
    this.dia = dia;
}

public int getMes() {
    return mes;
}

public void setMes(int mes) {
    this.mes = mes;
}

public int getAnyo() {
    return anyo;
}

public void setAnyo(int anyo) {
    this.anyo = anyo;
}
public void mostraData(int fecha){

}
public void calculaSemanaMes(){}
public void calculaSemanaAnyo(){}
public void esAnyoExtraordinario() {}
public void calculaDiaSemana(){}
public void esFestivo(){}
public void esLaborable(){}
public void fechaFormat(){}
}
    
asked by anonymous 30.05.2015 / 22:23

2 answers

0

You can use String#format() to include leading zeros.

String foo = String.format("%08d", 1234); // 00001234

In this example, a formatted String of size 8 will be returned where, to complete the missing size (in this case, eight) will be inserted 0 on the left. Some examples:

String.format("%010d", 123); //0000000123 (incluiu 7 zeros, tamanho 10)
String.format("%05d", 123);  //00123      (incluiu 2 zeros, tamanho 5 )
String.format("%010d", 1);   //0000000001 (incluiu 9 zeros, tamanho 10)

Then your method might look like this:

public String mostraData(String data) {
    String[] array = data.split("/");

    // Não é uma entrada x/x/x, então retorna a própria data
    if (!(array.length == 3)) return data;

    data = "";
    for (String each : array)
        data += String.format("%02d/", Integer.parseInt(each));
    // remove a última "/" do String#format antes de retornar
    return data.substring(0, data.length() -1);
}

When called:

mostraData("10/2");      // Mostra a própria data inserida: 10/2
mostraData("10/2/2015"); // 10/02/2015
mostraData("5/2/2015");  // 05/02/2015
mostraData("10/12/15");  // 10/12/15

Example on Ideone

    
30.05.2015 / 23:39
0

So:

int numero = 20102015
char[] digitos = String.valueOf( numero ).toCharArray();

//desta forma, digito[0]+digito[1] = 20, digito[2]+digito[3] = 10, digito[4]+digito[5]+digito[6]+digito[7] = 2015;
//Dae, so vc atribuir na respectiva variavel.
    
30.05.2015 / 22:51