Páginas

sábado, 25 de mayo de 2013

Calendar to String and String to Calendar (Android - java)

How many times did you think in convert a date, that it is on String type, to Calendar type? And Calendar to String?. I sure, at least, one in your developer lifes. I want to share a very easy way to do that, and this way is what i do. If you want to do the way Calendar to String:

Calendar fecha_calendar = Calendar.getInstance(); // or whatever date you set

CharSequence fecha_charsequence = fecha_DateFormat.format("yyyy-MM-dd", c); 

String fecha_string = fecha_charsequence.toString(); // Strings are CharSequence so this step is not necessary.

So simple, so fantastic!. You can see more information about DateFormat class (Android) here Let's see its inverse case.

Calendar fecha_calendar = Calendar.getInstance(); 

String fecha_string = "2013-5-24";

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 

try 
{
 Date fecha_date = sdf.parse(fecha_string);
 fecha_calendar.setTime(fecha_date);
    
} catch (ParseException e) {

 Log.v("printf", "ERROR!: can not parsing! ");
}

It is a longer way (a little bit) but it is still simple and easy. If you know another way simpler or different, let me know. Remember this: If you are using dates in your project, parse it before you use it. Always. Don't forget it by experience with working with databases( "2013-5-24" ¡NO!, "2013-12-3" ¡NO!, 2013-12-12 ¡YES!. tell me if you know why. ;) ).