简体   繁体   中英

Set Calendar to first week of a month in Java

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.

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

 Calendar c = Calendar.getInstance();   // this takes current date
    c.set(Calendar.DAY_OF_MONTH, 1);

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);

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM