1

First of all let me say that yes, I've researched this quite a lot and used a variety of solutions but nothing is working.

So I'm trying to get yesterday's date into a textview. I'm using this code:

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MMMM/d");
String strDate = sdf.format(cal.getTime());
tvDate.setText(strDate);

(I know this returns today's date, but at this point I'm just trying to get anything)

What happens is once I get from the previous activity to this one it immediately shuts down. If I comment the 3 lines in the middle and setText to a random string like "bla bla", the activity runs and displays it correctly. Android Studio is not displaying any errors in there so I have zero idea what's going on.

I've tried all the solutions in the following posts, all unsuccessfully, so I can only imagine there's some configuration I'm missing. 1 - Android get current date and show it in TextView 2 - Get current time and date on Android 3 - Display the current time and date in an Android application

I've also checked some Youtube videos but none had the answer.

Can you help ?

ruiBarbs
  • 13
  • 4

2 Answers2

1

I tested your code and it works fine for me, returning 2017/April/16. Make sure that your import statements at the top of your class-file are correct. They should be:

import java.text.SimpleDateFormat;
import java.util.Calendar;

To get yesterday's date, add the following line:

cal.add(Calendar.DATE, -1);
Miraduro
  • 229
  • 1
  • 9
  • that was it! My imports were `import android.icu.text.SimpleDateFormat; import android.icu.util.Calendar;` that were added automatically by Android Studio – ruiBarbs Apr 17 '17 at 14:51
0

Please check the below code

import java.util.Date;
import java.util.Calendar;

public class Main{

public static void main(String ar[]){
Calendar cal  = Calendar.getInstance();

System.out.println("Today's date= "+cal.getTime());
//subtracting a day
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date= "+cal.getTime());

}

}