viernes, 15 de junio de 2012

Transformar Date to String java

 
Transforma una fecha en string. Ademas obtiene la hora de la fecha.


private static void trasformarDateToString(){
     java.util.Date date = new java.util.Date();
     java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm");
    String fecha = sdf.format(date);

System.out.println("fecha y hora "+fecha);
int indice=fecha.indexOf(" ");
System.out.println(" hora "+fecha.substring(indice, fecha.length()));

   }

viernes, 8 de junio de 2012

Calcular años

 private static void calcularAnnos(){
      Date fechaNacimiento=new Date(87, 05, 8);
      Date fechaHoy =new Date();
      DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
      System.out.println("Fecha nacimiento:"+dateFormat.format(fechaNacimiento));
      System.out.println("Fecha nacimiento:"+dateFormat.format(fechaHoy));
      int edad=fechaHoy.getYear()-fechaNacimiento.getYear();
      System.out.println("Edad:"+edad);
      System.out.println(fechaNacimiento.getMonth()+" "+fechaHoy.getMonth());
      if((fechaNacimiento.getMonth()-fechaHoy.getMonth())>0){
        edad--;
      }
 else if((fechaNacimiento.getMonth()-fechaHoy.getMonth())==0){
     System.out.println(fechaNacimiento.getDate()+" "+fechaHoy.getDate());
       if((fechaNacimiento.getDate()-fechaHoy.getDate())>0){
       edad--;
       }
 }

       System.out.println("Edad:"+edad);
    }