Método para validar fechas en Java

import java.text.SimpleDateFormat;
import java.text.ParseException;

public boolean validarFecha(String fecha) {

if (fecha == null)
return false;

SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyy-MM-dd”); //año-mes-dia

if (fecha.trim().length() != dateFormat.toPattern().length())
return false;

dateFormat.setLenient(false);

try {
dateFormat.parse(fecha.trim());
}
catch (ParseException pe) {
return false;
}
return true;
}

Un detalle es que si le das como entrada 2009-5-5 la función va a retornar false, la forma correcta sería 2009-05-05


Fuente

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
  • Identi.ca
  • LinkedIn
  • PDF
  • RSS
  • Twitter
This entry was posted in desarrollo, java and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>