I have A string which is String dateOfOrder = "01/06/2019";
I would like to get the number of days in Week 1 as June first week only have 1 day.
May i know how do i approach on receviing number of days in Week X ?
Like In June 2019
Week 1 : Have 1 day Week 2 - 5 : have 7 days Week 6 : Have 1 day
EDIT
I'm thinking of this approach of getting number of days in a week whereby I have a couple of String arrayList. For example on my given date above, if Week 1 Have Saturday. Week 1 Array List will add saturday in it and .size(). If Week 2 have Sunday to Saturday, it will add all the dates in the Week 2 Array List and .size() to get the number of days in the ArrayList. Lastly, The last week of June which is Week 6 will have Sunday only and it will add into Week 6 ArrayList and have value of Sunday only and .size() to get 1.
I'm wondering if its the best approach and I'm not sure if i can get the correct days in the week.
Parse the string as date using SimpleDateFormatter
. Your parsing pattern could be dd/MM/YYYY
.
DateFormat df = new SimpleDateFormat("dd/MM/YYYY");
Date date = df.parse(dateOfOrder);
Once you have the date, get day of week using Calendar
.
Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
Calculate number of days in the given week (and month).
int daysInMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
int currentMonth = c.get(Calendar.MONTH);
int prevWeekMonth = c.add(Calendar.DAY_OF_MONTH, -7).get(Calendar.MONTH);
c.setTime(yourDate);
int nextWeekMonth = c.add(Calendar.DAY_OF_MONTH, 7).get(Calendar.MONTH);
c.setTime(yourDate);
if (prevWeekMonth != currentMonth) {
// first or second week
if (dayOfMonth > dayOfWeek) {
// second week
numOfDaysInWeek = 7;
} else {
// first week
int firstDay = c.set(Calendar.DAY_OF_MONTH, 1).get(Calendar.DAY_OF_WEEK);
numOfDaysInWeek = 7 - firstDay;
}
} else if (nextWeekMonth != currentMonth) {
// last or second last week
if (dayOfMonth - dayOfWeek + 7 >= daysInMonth) {
// last week
numOfDaysInWeek = c.set(Calendar.DAY_OF_MONTH, daysInMonth).get(Calendar.DAY_OF_WEEK);
} else {
// second last week
numOfDaysInWeek = 7;
}
} else {
// middle weeks
numOfDaysInWeek = 7;
}
Note: the conditions are a bit rough and you might need to add 1
depending on whether dayOfWeek, dayOfMonth have 0 or 1 index.
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.