Bom dia pessoal,
Como sempre que tenho alguma duvida, sobre algo relacionado a java o forum geralmente me ajuda resolvi contribuir tambem.
Vou postar 2 metodos abaixo que valida datas no j2me, visto que em j2me nao temos as classes que fazem isso facilmente no J2se ou J2ee. Deixo claro que a implementaçao do metodo isBisseto() nao foi feito por mim, foi copiado deste tópico aqui http://www.javafree.org/javabb/viewtopic.jbb?t=13682 . O codigo nao e o mais otimizado possivel, porem realiza com sucesso a validaçao das datas no formato xx/xx/xxxx entre 2006 e 2100, segue o codigo:
private boolean validateDate( String x )
{
if( textfield.getString().length() != 10 )
{
return false;
}
String[] dias = { "01", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" };
String[] meses = { "01", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" };
String dia = null;
String mes = null;
String ano = null;
String dataCompleta = x;
if( !dataCompleta.substring( 2, 3 ).equals( "/" ) || !dataCompleta.substring( 5, 6 ).equals( "/" ) )
{
return false;
}
dia = dataCompleta.substring( 0, 2 );
mes = dataCompleta.substring( 3, 5 );
ano = dataCompleta.substring( 6, 10 );
if( dia.equals( "29" ) && mes.equals( "02" ) && !isBissexto( Integer.parseInt( ano ) ) )
{
return false;
}
boolean anoOk = false;
boolean mesOk = false;
boolean diaOk = false;
String milhar = ano.substring( 0, 1 );
System.out.println( "milhar " + milhar );
if( milhar.equals( "2" ) )
{
String centena = ano.substring( 1, 4 );
System.out.println( "centena" + centena );
for( int i = 006; i <= 100; i++ )
{
if( Integer.parseInt( centena ) == i )
{
anoOk = true;
}
}
}
for( int i = 0; i < meses.length; i++ )
{
if( mes.equals( meses[i] ) )
{
mesOk = true;
}
}
for( int i = 0; i < dias.length; i++ )
{
if( dia.equals( dias[i] ) )
{
diaOk = true;
}
}
if( anoOk && mesOk && diaOk )
{
return true;
}
return false;
}
metodo isBissexto()
public static boolean isBissexto( int year )
{
// Ano antes de cristo se adiciona + 1.
if( year < 0 )
return ( ( year + 1 ) & 3 ) == 0;
// Antes de 1582 não existe a regra dos 100 anos
if( year < 1582 )
return ( year & 3 ) == 0;
// Se for divisível por quatro não por 100.
if( ( year & 3 ) == 0 && year % 100 != 0 )
return true;
// última chance ser for múltiplo de 400
return ( year % 400 == 0 );
}
espero que ajude, criticas e sugestoes sao somrep construtivas.
um abraço.
OBS: Nao sei se era aqui mesmo no forum que eu deveria colcoar esse codigo de ajuda, se nao for por favor me mostre onde colocar.
grato.