Android Studio - Convert a String field to Date

1

Good morning, I am using a String field called "fecha_ini" and it contains a date in the following format "01-02-2018". What I need is to add one day to this date, but for that first I have to cast it from String to Date if I'm not mistaken. To do the casting I tried the following, but it throws me error:

    fecha_ini = "01-02-2018";

    try
    {
        String fecha = fecha_ini;
        SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-aaaa");
        java.util.Date dateOjb = format1.parse(fecha);
        SimpleDateFormat format2 = new SimpleDateFormat("dd/MM/aaaa");
        nuevaFecha = format2.format(dateOjb);
        Toast.makeText(this,nuevaFecha , Toast.LENGTH_SHORT).show();
    }catch(ParseException e){
    }

The error is this:

  

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length ()' on a null object reference

Am I doing it right or is there another easier way to convert the "date_ini" field to Date? To then be able to work with the result and add days.

Thank you very much.

    
asked by Rodrigo 29.11.2018 в 15:19
source

2 answers

0

You can add this to add a day to the date

Date dt = new Date();
Calendar c = Calendar.getInstance(); 
c.setTime(dt); 
c.add(Calendar.DATE, 1);
dt = c.getTime();

or just do this

Date today = new Date();
Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));

This example is echoed in Kotlin, only edited to Java

 val date = Date()
 val c = Calendar.getInstance()
 c.time = date
 c.add(Calendar.DATE, 1)
 val simpleDateFormat1 = SimpleDateFormat("dd-MM-yyyy", Locale.US)
            val todayCalendar = simpleDateFormat1.format(c.time)
Log.i("TAG", "" + todayCalendar)
    
answered by 29.11.2018 в 17:45
-1

You can try the following:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String strDate = "2000-01-01";
Date date = new Date(sdf.parse(strDate).getTime());
    
answered by 29.11.2018 в 15:43