0

Hi I am working on a project where I need to get the date of the first day of the week in format of yyyy-MM-dd and show it in a TextView, I tried this solution but I got confused with using Date and Calendar classes, I tried the below code but always I get the complete date string or wrong date my overall purpose is to get date of the first day of the week any one who write the code to do this or explain the difference between Date and Calendar classes I would appreciate. Thanks here is the code

 int year, month, day;

    tvTest = (TextView) findViewById(R.id.tvTheoryStudies);

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);


    year = cal.get(Calendar.YEAR);
    month = cal.get(Calendar.MONTH);
    day = cal.get(Calendar.DAY_OF_MONTH);
    String todayDate = new StringBuilder().append(year).append("-").append(month).append("-").append(day).toString();


    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    cal.set(Calendar.DAY_OF_WEEK, 1);
    Date date =new Date();

    try {
        date = sdf.parse(todayDate);
    }
    catch (Exception e){
        e.printStackTrace();
    }


    cal.setTime(date);
    date = cal.getTime();
    tvTest.setText(date.toString());
Community
  • 1
  • 1
Elham Kohestani
  • 3,013
  • 3
  • 20
  • 29

1 Answers1

2

You are making it much more complicated than it needs to be.

The code below will give you what you want:

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String outputDate = simpleDateFormat.format(calendar.getTime());

Calendar.getInstance() gives a Calendar object set to todays date.
Then i set the DAY_OF_WEEK to MONDAY (note that Calendar.MONDAY's constant value is 2, not 1. This can be seen in the documentation).
I set up a SimpleDateFormat with the correct format, and then i use getTime() on the calendar object to get a Date object which i pass to the SimpleDateFormat.

The difference between the Date class and the Calendar class is that the Calendar class is used to do manipulations on the date (add, subtract, compare, etc), while the Date class is simply used to hold a date, and print it to the screen for the user to see.

So you should always have a Calendar object in the code, and then convert it as i do above, when showing it to the user. The Calendar class has ALOT more functions to work with than the Date class, and it's generally easier.

Moonbloom
  • 7,738
  • 3
  • 26
  • 38