[RESOLVIDO]como comparar data?

8 respostas
vinnyparker

Ola pessoal, eu tou fazendo uma consulta e eu tenho alguns campos de data. o que eu quero eh, checar se a data for tal, faça isso, se nao faça akele outro ou nao faça nada…

meu codigo ta assim:

public void init (String _folder){
		super.init(_folder);
		this.dbfName = "PAY2_002";
	}
	
	@Override
	public Object next() {
		Folha bean = null;
		String fieldValue = "";
		Object[] record = null;
		
		try{
			if (this.hasNext()){
				this.recNo++;
				record = this.dbfFile.nextRecord();
				
				
				String ano = null;
				String ano2 = null;
				String mes = null;
				String funcionario = null;
				int tipoFolha = 1;
				String movimento = null;
				String controleAno = null;
				String controleMes = null;
				int dia  = 0;

		for (int i =0; i < this.dbfFile.getFieldCount(); i++){
			DBFField field = this.dbfFile.getField(i);
			
			if ((record[i] != null) && (!record[i].equals (""))){
				
				if ("MOVIMENTO".equals(field.getName())){
					fieldValue = (((String) record [i]).trim());
					controleAno = (StrHelper.substringBefore(fieldValue, "/"));
					System.out.println("ControleAno->> "+controleAno);
				}
				
				if ("MOVIMENTO".equals(field.getName())){
					fieldValue = (((String) record [i]).trim());
					controleMes = (StrHelper.substringAfter(fieldValue, "/"));
					System.out.println("ControleMes->> "+controleMes);

				}
			if ("2010".equalsIgnoreCase(controleAno)){    // Este teste aqui nao ta funcionando, sem ele passa tudo normal
				if ("03".equalsIgnoreCase(controleMes)){
					
					if ("MOVIMENTO".equals(field.getName())){
					fieldValue = (((String) record [i]).trim());
					ano = (StrHelper.substringBefore(fieldValue, "/"));
				}
				
				if ("MOVIMENTO".equals(field.getName())){
					fieldValue = (((String) record [i]).trim());
					ano2 = (StrHelper.substringBefore(fieldValue, "/"));
				}
				
				if ("MOVIMENTO".equals(field.getName())){
					fieldValue = (((String) record [i]).trim());
					mes = (StrHelper.substringAfter(fieldValue, "/"));
				}
				
				if ("MOVIMENTO".equals(field.getName())){
					fieldValue = (((String) record [i]).trim());
					movimento = (StrHelper.removeSigns(fieldValue));
				}
				
				if ("FUNCC".equals(field.getName())){
					fieldValue = (((String) record [i]).trim());
					funcionario = (StrHelper.removeSigns(fieldValue));
					System.out.println("Funcionario.fildvalue >>"+funcionario);
				}
				
			}
			
					
		}
				
		/**inicio dos tratamentos**/
		if(funcionario.startsWith("0000")){
			funcionario = (StrHelper.removeStart(funcionario, "0000" ));
		}
		else
			if(funcionario.startsWith("000")){
				funcionario = (StrHelper.removeStart(funcionario, "000" ));
			} 
			else
				if(funcionario.startsWith("00")){
					funcionario = (StrHelper.removeStart(funcionario, "00" ));
				}
		
		if ("01".equalsIgnoreCase(mes)||
		    "03".equalsIgnoreCase(mes)||
		    "05".equalsIgnoreCase(mes)||
		    "07".equalsIgnoreCase(mes)||
		    "08".equalsIgnoreCase(mes)||
		    "10".equalsIgnoreCase(mes)||
		    "12".equalsIgnoreCase(mes)){
			dia=31;
		}
		else
			if("04".equalsIgnoreCase(mes)||
			   "06".equalsIgnoreCase(mes)||
			   "09".equalsIgnoreCase(mes)||
			   "11".equalsIgnoreCase(mes)){
				dia=30;
			}
		else
			dia=28;	
		
		
		int folha = contadorfolha++;
		System.out.println("Folha->> "+folha);
		
		int ano3 = Integer.parseInt(ano);
		System.out.println("ano3->> "+ano3);

		int mes2 = Integer.parseInt(mes);
		System.out.println("mes->> "+mes2);
		System.out.println("dia->> "+dia);

		Date data = DateHelper.parse(ano3, mes2-1, dia);
		System.out.println("data->> "+data);

		int funcionarios = Integer.parseInt(funcionario);
		System.out.println("funcionarios->>"+funcionarios);
		
		String folha3 = (movimento +funcionario);
		
		int folha4 = (Integer.parseInt(folha3));
		
		Date dataCompare = (DateHelper.parse(2010, 03, 31));
			
		
		/**fim dos tratamentos**/

	//	if (DateHelper.isSameInstant(dataCompare, data)){
			
		
		
		if(checarFolha(folha4)){
		bean = new Folha();
		
		bean.setAno(ano3);
		bean.setData(data);
		bean.setFolha(folha);
		bean.setFuncionarios(funcionarios);
		bean.setTipoFolha(tipoFolha);
		System.out.println("funcionario.bean.->>"+funcionarios);
		
		
		}

		}
//	} 
		
		}
			}
			
		}catch (DBFException e) {
			_logger.error(e.getMessage());
		}

		// TODO Auto-generated method stub
		return bean;
	}
	/**List**/	


	List listaFolha = new ArrayList<Integer>();

	public boolean checarFolha(int folha){     /***Testa se a folha ja foi alncada
												para nao duplicar a folha****/
		if(listaFolha.contains(folha)){

			return false;

		}
		else{

			listaFolha.add(folha);

			return true;

		}

	}

	/**fim da List**/

}

E ta dando esse erro aqui ó:

INFO [Thread-1] (_Quimera.java:41) - Criada pasta: files/1052/dprh nome: /br/com/link3/dp/convert/rh/quimera file:/home/vinny/workspace/l3convert/bin/br/com/link3/dp/convert/rh/quimera versão DBase: 2.03 ControleAno->> 2001 ControleMes->> 01 Exception in thread "Thread-1" java.lang.NullPointerException at br.com.link3.dp.convert.rh.quimera.FolhaDao.next(FolhaDao.java:110) at br.com.link3.dp.convert.ConvertManager.export(ConvertManager.java:259) at br.com.link3.dp.convert.ConvertManager.processa(ConvertManager.java:132) at br.com.link3.dp.convert.MainForm$5.run(MainForm.java:348)

8 Respostas

francislei.reis

Cara tu já debugou este código?

Se ão, debuga e vê onde está dando NullPointerException

L

Cara se tu quer comparar datas use Um Calendar em vez de tipos String e Date,naum eh a ultima bolacha do pacote mas ajuda um pouco.
pesquise aki no forum msm que tem milhares de topicos sobre isso.
t+

vinnyparker

o erro ta dando aqui ó:

#     /**inicio dos tratamentos**/  
#         if(funcionario.startsWith("0000")){  
#             funcionario = (StrHelper.removeStart(funcionario, "0000" ));  
#         }  
#         else  
#             if(funcionario.startsWith("000")){  
#                 funcionario = (StrHelper.removeStart(funcionario, "000" ));  
#             }   
#             else  
#                 if(funcionario.startsWith("00")){  
#                     funcionario = (StrHelper.removeStart(funcionario, "00" ));  
#                 }
francislei.reis

Quando explode o erro a sua variável "FUNCIONARIO"está nula?

pmlm

Essa variável field é muito inconstante, não? Deve estar sempre a mudar de valor para teres de repetir sempre o mesmo teste :slight_smile:

vinnyparker

pmlm:
vinnyparker:

if ("MOVIMENTO".equals(field.getName())){
					fieldValue = (((String) record [i]).trim());
					ano2 = (StrHelper.substringBefore(fieldValue, "/"));
				}
				
				if ("MOVIMENTO".equals(field.getName())){
					fieldValue = (((String) record [i]).trim());
					mes = (StrHelper.substringAfter(fieldValue, "/"));
				}
				
				if ("MOVIMENTO".equals(field.getName())){
					fieldValue = (((String) record [i]).trim());
					movimento = (StrHelper.removeSigns(fieldValue));
				}


Essa variável field é muito inconstante, não? Deve estar sempre a mudar de valor para teres de repetir sempre o mesmo teste :-)

Essa variavel é composta por: “ano/mes”
eu preciso de um campo ano, um campo data, e ainda uso o campo movimento para compor minha ID, por isso ela eh testada varias vezes.
Ela esta sendo tratada como uma String, um substring antes da barra, um substring depois da barra e um remove sings para pegar os campos sem a barra

pmlm

E porque não tudo dentro do mesmo if?

vinnyparker

Bom, consegui resolver isso, simplesmente trocando o teste de lugar.
Eu pus o teste antes de iniciar o bean.
entao ele testa tudo e so monta o bean se obedecer ao criterio do teste.
Ficou assim:

/**
 * @author vinny
 *
 *
 */
package br.com.link3.dp.convert.rh.quimera;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JSpinner.DateEditor;

import jxl.biff.StringHelper;

import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;

import br.com.link3.dp.model.rh.Folha;
import br.com.link3.dp.tools.DateHelper;
import br.com.link3.dp.tools.StrHelper;

import com.linuxense.javadbf.*;


public class FolhaDao extends _QuimeraDao{
    private Logger _logger = Logger.getLogger(FolhaDao.class);
    protected static int contadorfolha = [telefone removido];

    
    public void init (String _folder){
        super.init(_folder);
        this.dbfName = "PAY2_002";
    }
    
    @Override
    public Object next() {
        Folha bean = null;
        String fieldValue = "";
        Object[] record = null;
        
        try{
            if (this.hasNext()){
                this.recNo++;
                record = this.dbfFile.nextRecord();
                
                
                String ano = null;
                String ano2 = null;
                String mes = null;
                String funcionario = null;
                int tipoFolha = 1;
                String movimento = null;
                String controleAno = null;
                String controleMes = null;
                int dia  = 0;

        for (int i =0; i < this.dbfFile.getFieldCount(); i++){
            DBFField field = this.dbfFile.getField(i);
            
            if ((record[i] != null) && (!record[i].equals (""))){
                
                if ("MOVIMENTO".equals(field.getName())){
                    fieldValue = (((String) record [i]).trim());
                    controleAno = (StrHelper.substringBefore(fieldValue, "/"));
                    System.out.println("ControleAno->> "+controleAno);
                }
                
                if ("MOVIMENTO".equals(field.getName())){
                    fieldValue = (((String) record [i]).trim());
                    controleMes = (StrHelper.substringAfter(fieldValue, "/"));
                    System.out.println("ControleMes->> "+controleMes);

                }
                    
                    if ("MOVIMENTO".equals(field.getName())){
                    fieldValue = (((String) record [i]).trim());
                    ano = (StrHelper.substringBefore(fieldValue, "/"));
                }
                
                if ("MOVIMENTO".equals(field.getName())){
                    fieldValue = (((String) record [i]).trim());
                    ano2 = (StrHelper.substringBefore(fieldValue, "/"));
                }
                
                if ("MOVIMENTO".equals(field.getName())){
                    fieldValue = (((String) record [i]).trim());
                    mes = (StrHelper.substringAfter(fieldValue, "/"));
                }
                
                if ("MOVIMENTO".equals(field.getName())){
                    fieldValue = (((String) record [i]).trim());
                    movimento = (StrHelper.removeSigns(fieldValue));
                }
                
                if ("FUNCC".equals(field.getName())){
                    fieldValue = (((String) record [i]).trim());
                    funcionario = (StrHelper.removeSigns(fieldValue));
                    System.out.println("Funcionario.fildvalue >>"+funcionario);
                }
                
            }
            
                    
        }
                
        /**inicio dos tratamentos**/
        if(funcionario.startsWith("0000")){
            funcionario = (StrHelper.removeStart(funcionario, "0000" ));
        }
        else
            if(funcionario.startsWith("000")){
                funcionario = (StrHelper.removeStart(funcionario, "000" ));
            } 
            else
                if(funcionario.startsWith("00")){
                    funcionario = (StrHelper.removeStart(funcionario, "00" ));
                }
        
        if ("01".equalsIgnoreCase(mes)||
            "03".equalsIgnoreCase(mes)||
            "05".equalsIgnoreCase(mes)||
            "07".equalsIgnoreCase(mes)||
            "08".equalsIgnoreCase(mes)||
            "10".equalsIgnoreCase(mes)||
            "12".equalsIgnoreCase(mes)){
            dia=31;
        }
        else
            if("04".equalsIgnoreCase(mes)||
               "06".equalsIgnoreCase(mes)||
               "09".equalsIgnoreCase(mes)||
               "11".equalsIgnoreCase(mes)){
                dia=30;
            }
        else
            dia=28;    
        
        
        int folha = contadorfolha++;
        System.out.println("Folha->> "+folha);
        
        int ano3 = Integer.parseInt(ano);
        System.out.println("ano3->> "+ano3);

        int mes2 = Integer.parseInt(mes);
        System.out.println("mes->> "+mes2);
        System.out.println("dia->> "+dia);

        Date data = DateHelper.parse(ano3, mes2-1, dia);
        System.out.println("data->> "+data);

        int funcionarios = Integer.parseInt(funcionario);
        System.out.println("funcionarios->>"+funcionarios);
        
        String folha3 = (movimento +funcionario);
        
        int folha4 = (Integer.parseInt(folha3));
        
        Date dataCompare = (DateHelper.parse(2010, 03, 31));
            
        
        /**fim dos tratamentos**/
      

  if ("2010".equalsIgnoreCase(controleAno)){     //testa o ano e  o mes e so monta o bean se obedecer a este criterio
            if ("03".equalsIgnoreCase(controleMes)){
        
        
        //if (DateHelper.isSameInstant(dataCompare, data)){
            
        
        
        if(checarFolha(folha4)){
        bean = new Folha();
        
        bean.setAno(ano3);
        bean.setData(data);
        bean.setFolha(folha4);
        bean.setFuncionarios(funcionarios);
        bean.setTipoFolha(tipoFolha);
        System.out.println("funcionario.bean.->>"+funcionarios);
        
        
        }

        }
//    } 
        
        }
            }
            
        }catch (DBFException e) {
            _logger.error(e.getMessage());
        }

        // TODO Auto-generated method stub
        return bean;
    }
    /**List**/    


    List listaFolha = new ArrayList<Integer>();

    public boolean checarFolha(int folha){     /***Testa se a folha ja foi lancada
                                                para nao duplicar a folha****/
        if(listaFolha.contains(folha)){

            return false;

        }
        else{

            listaFolha.add(folha);

            return true;

        }

    }

    /**fim da List**/

}
Criado 13 de setembro de 2010
Ultima resposta 14 de set. de 2010
Respostas 8
Participantes 4