Reputation: 95
i'm trying to set Calendar object -> today to a particular day of first week of a month.
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
today.clear(Calendar.MINUTE);
today.clear(Calendar.SECOND);
today.clear(Calendar.MILLISECOND);
today.getTime();
today.set(Calendar.YEAR,year);
today.set(Calendar.MONTH, month);
today.set(Calendar.WEEK_OF_MONTH,today.getActualMinimum(Calendar.WEEK_OF_MONTH));
today.set(Calendar.DAY_OF_WEEK, getDay()+1);
Log.d(TAG, "Test : "+getName()+", time : "+ today.getTime()+" ,year : "+year+" ,month : "+ month);
problem is, the calendar is returning the date of day set of current week.
Upvotes: 1
Views: 2078
Reputation: 2403
You can use the below code. It will return the date as same day as of today but for first week of month.
public String getDayFromFirstWeek() {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
Calendar date = Calendar.getInstance(Locale.getDefault());
date.set(Calendar.DAY_OF_MONTH, 1);
date.add(Calendar.DAY_OF_YEAR, (date.get(Calendar.DAY_OF_WEEK)+ Calendar.getInstance().get(Calendar.DAY_OF_WEEK) - 1) % 7);
return formatter.format(date.getTime());
}
Upvotes: 0
Reputation: 701
Use below code:
public static String getEightWeeksDateString() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-01 00:00:00");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 0);
return dateFormat.format(cal.getTime());
}
This return Date in string format, then you should convert it into what u want
Upvotes: 3
Reputation: 30
There is a DAY_OF_MONTH field in class calendar, which you are required to change if you want to accomplish your goal. Look in documentation. You just need to use set method :
today.set(Calendar.DAY_OF_MONTH, 1);
Upvotes: 0
Reputation: 79
Calendar c = Calendar.getInstance(); // this takes current date
c.set(Calendar.DAY_OF_MONTH, 1);
Upvotes: 0