Manthri Anvesh
Manthri Anvesh

Reputation: 95

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.

Upvotes: 1

Views: 2078

Answers (4)

Sanjeet
Sanjeet

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

Pranay Kumbhalkar
Pranay Kumbhalkar

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

Wiktor Sznyra
Wiktor Sznyra

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

theendcomplete
theendcomplete

Reputation: 79

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

Upvotes: 0

Related Questions