This question already has answers here:
How can I add business days to the current date in Java?
(14 answers)
Closed 6 years ago.
How can I increment the day with skipping weekends. I mean if day=Friday then day+1=Monday. Please take a look at my increment method which I increment a calendar day and not a Business day
public Date incDay( Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 1);
return cal.getTime();
}
I need to modify this method for resolve this issue.
Update:
I update my method like this
public Date incDay(Date date){
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
// public final static int FRIDAY = 6;
final int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.FRIDAY) {
cal.add(Calendar.DATE, 3);
}else{
cal.add(Calendar.DATE, 1);
}
System.out.println(cal.getTime());
return cal.getTime();
}
Main():
public static void main(String[] args) throws ParseException {
Date d=incBusiness(new Date(2017, 02, 17));//2017/02/18
}
I got 2017/02/18 instead of 2017/02/20
Calendar class has constants to check the day of the week:
FRIDAY is the 6th day of the week, doing an if-else can resolve the issue...
public static void foo() throws ParseException {
String dateString = "2017/02/17";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");// "2017/02/17";
Date date = df.parse(dateString);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
cal.add(Calendar.DATE, 3);
} else {
cal.add(Calendar.DATE, 1);
}
System.out.println(cal.getTime());
}
Gets date instance and add no. of days excluding weekends. Set date to next monday if provided date is weekend.
public Date addDays(Date date, int days){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
//set date to next monday if provided date day is weekend
//use this section according to your need.
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
cal.add(Calendar.DATE,2);
//days-= 2;
}else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
cal.add(Calendar.DATE,1);
//days--;
}
//add days one by one
while(days > 0){
//if current day is friday add 3 days to skip saturday and sunday
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY){
cal.add(Calendar.DATE,3);
//else add one day
}else{
cal.add(Calendar.DATE,1);
}
//decrements day counter
days--;
}
return cal.getTime();
}
Related
I needed to define start/end dates for a person's given age. This seemed simple:
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dateOfBirth);
cal.add(Calendar.YEAR, years);
Date start = cal.getTime();
cal.add(Calendar.YEAR, 1);
cal.add(Calendar.DAY_OF_MONTH, -1);
Date end = cal.getTime();
Ah, but then there are those born on Leap Day Feb 29th. If the age is not a multiple of 4 then Calendar will round down to the 28th. In this case, my code above will give a date range ending on Feb 27th, and there'll be a gap.
So, I can easily solve this by checking for this condition, and I can wrap the fix up in some method to avoid duplicating it everywhere. But I'm wondering, is there a better solution I'm not aware of? Something that automatically accounts for this special case for a "day before/after" problem?
Here's my solution:
public static Date getAgeStartEnd(Date d, int age, boolean end) {
if (d == null) return null;
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(d);
int baseDay = cal.get(Calendar.DAY_OF_MONTH);
cal.add(Calendar.YEAR, age + (end ? 1 : 0));
int newDay = cal.get(Calendar.DAY_OF_MONTH);
boolean roundedDown = baseDay != newDay;
if (end && !roundedDown)
cal.add(Calendar.DAY_OF_MONTH, -1);
else if (!end && roundedDown)
cal.add(Calendar.DAY_OF_MONTH, 1);
d = cal.getTime();
return d;
}
Date start = getAgeStartEnd(dateOfBirth, years, false);
Date end = getAgeStartEnd(dateOfBirth, years, true);
How to get all dates in the calendar in current/some month?
for example for this month, like the picture
So the result is ["07-31-2016", "08-01-2016", "08-02-2016" ... "08-31-2016", "09-01-2016", "09-02-2016", "09-03-2016"]
Any ideas?, thanks in advance.
Well, with Calendar and its constants you can achieve this quite easy:
Given month and year get first day of the month and place calendar on monday:
Calendar start = Calendar.getInstance();
start.set(MONTH, month - 1); // month is 0 based on calendar
start.set(YEAR, year);
start.set(DAY_OF_MONTH, 1);
start.getTime(); // to avoid problems getTime make set changes apply
start.set(DAY_OF_WEEK, SUNDAY);
if (start.get(MONTH) <= (month - 1)) // check if sunday is in same month!
start.add(DATE, -7);
Given month and year get last day of month and move calendar to sunday
Calendar end = Calendar.getInstance();
end.set(MONTH, month); // next month
end.set(YEAR, year);
end.set(DAY_OF_MONTH, 1);
end.getTime(); // to avoid problems getTime make set changes apply
end.set(DATE, -1);
end.set(DAY_OF_WEEK, SATURDAY);
if (end.get(MONTH) != month)
end.add(DATE, + 7);
Test it:
public static void main(String[] args) {
int month = 8, year = 2016;
Calendar start = Calendar.getInstance();
start.set(MONTH, month - 1); // month is 0 based on calendar
start.set(YEAR, year);
start.set(DAY_OF_MONTH, 1);
start.getTime();
start.set(DAY_OF_WEEK, SUNDAY);
if (start.get(MONTH) <= (month - 1))
start.add(DATE, -7);
System.out.println(printCalendar(start));
Calendar end = Calendar.getInstance();
end.set(MONTH, month); // next month
end.set(YEAR, year);
end.set(DAY_OF_MONTH, 1);
end.getTime();
end.set(DATE, -1);
end.set(DAY_OF_WEEK, SATURDAY);
start.getTime();
if (end.get(MONTH) != month)
end.add(DATE, + 7);
System.out.println(printCalendar(end));
}
Combined with:
import static java.util.Calendar.*;
and
private final static SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
private static String printCalendar(Calendar c) {
return df.format(c.getTime());
}
OUTPUT:
2016/07/31
2016/09/03
WITH
int month = 5, year = 2015;
OUTPUT:
2015/04/26
2015/06/06
Now, just iterate over starting Calendar adding +1 to Calendar.DATE in a while loop (in the example I split by weeks to be more clear):
int i = 1;
while (start.before(end)) {
System.out.print(printCalendar(start));
if (i % 7 == 0) { // last day of the week
System.out.println();
i = 1;
} else {
System.out.print(" - ");
i++;
}
start.add(DATE, 1);
}
OUTPUT:
2015/04/26 - 2015/04/27 - 2015/04/28 - 2015/04/29 - 2015/04/30 - 2015/05/01 - 2015/05/02
2015/05/03 - 2015/05/04 - 2015/05/05 - 2015/05/06 - 2015/05/07 - 2015/05/08 - 2015/05/09
2015/05/10 - 2015/05/11 - 2015/05/12 - 2015/05/13 - 2015/05/14 - 2015/05/15 - 2015/05/16
2015/05/17 - 2015/05/18 - 2015/05/19 - 2015/05/20 - 2015/05/21 - 2015/05/22 - 2015/05/23
2015/05/24 - 2015/05/25 - 2015/05/26 - 2015/05/27 - 2015/05/28 - 2015/05/29 - 2015/05/30
2015/05/31 - 2015/06/01 - 2015/06/02 - 2015/06/03 - 2015/06/04 - 2015/06/05 - 2015/06/06
java.time
You can use the nice java.time classes built into Java 8 and later. Both the above solutions work, this is a way to do in Java 8. Can be done with a little more brevity , split it just for understanding.
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
public class Clazz {
public static void main(String[] args) throws Exception {
LocalDate today = LocalDate.now();
LocalDate firstDayOfTheMonth = today.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDayOfTheMonth = today.with(TemporalAdjusters.lastDayOfMonth());
LocalDate squareCalendarMonthDayStart = firstDayOfTheMonth
.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
LocalDate squareCalendarMonthDayEnd = lastDayOfTheMonth
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY));
List<LocalDate> totalDates = new ArrayList<>();
while (!squareCalendarMonthDayStart.isAfter(squareCalendarMonthDayEnd)) {
totalDates.add(squareCalendarMonthDayStart);
squareCalendarMonthDayStart = squareCalendarMonthDayStart.plusDays(1);
}
totalDates.forEach(System.out::println);
}
}
Get the monday before the 1st of that month:
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(2016, 08, 01);
Calendar start = Calendar.getInstance();
start.setFirstDayOfWeek(Calendar.MONDAY);
start.setWeekDate(2016,c.getWeekYear(), Calendar.MONDAY);
Get the sunday after the last day of that month:
c.set(2016,08,31);
Calendar end = Calendar.getInstance();
end.setFirstDayOfWeek(Calendar.MONDAY);
end.setWeekDate(2016, c.getWeekYear(), Calendar.SUNDAY);
Then print all dates between start and end
Write a common method like this and use it -
fun getAllDateOfCurrentMonth(): List<LocalDate> {
val yearMonth= YearMonth.now()
val firstDayOfTheMonth = yearMonth.atDay(1)
val datesOfThisMonth = mutableListOf<LocalDate>()
for (daysNo in 0 until yearMonth.lengthOfMonth()){
datesOfThisMonth.add(firstDayOfTheMonth.plusDays(daysNo.toLong()))
}
return datesOfThisMonth
}
I found this method here:
public Date getLastFriday( int month, int year ) {
Calendar cal = Calendar.getInstance();
cal.set( year, month + 1, 1 );
cal.add( Calendar.DAY_OF_MONTH, -(cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ));
return cal.getTime();
}
I want similar functionality like this:
private Date getFirstThursday(Date now) {
Calendar cal = Calendar.getInstance();
cal.setTime(now);
cal.add(Calendar.DAY_OF_MONTH, ???);
return cal.getTime();
}
Can anyone help what I should replace? Marked with.
Try this code:
private static Date getFirstThursday(Date now) {
Calendar cal = Calendar.getInstance();
cal.setTime(now);
cal.set(Calendar.WEEK_OF_MONTH, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
return cal.getTime();
}
I'm new to Java
How do I get the total number of months between two (2) jdatechooser? I've search already about this but the date was set to the code, In my case I want to put the dates via JDateChooser.
I can do this through this code but if the year change I was not able to compute the total number of months I want to do this without using JodaTime.
Here is my code
public void month(){
int TotalMonth;
Calendar toDate;
Calendar fromDate;
int increment;
Date dt1 = date1.getDate(); //datechooser 1
Date dt2 = date2.getDate(); //datechooser 2
fromDate = Calendar.getInstance();
toDate = Calendar.getInstance();
if(dt1.after(dt2))
{
fromDate.setTime(dt2);
toDate.setTime(dt1);
}
else
{
fromDate.setTime(dt1);
toDate.setTime(dt2);
}
increment = 0;
TotalMonth = toDate.get(Calendar.MONTH) - (fromDate.get(Calendar.MONTH + increment));
jLabel2.setText(Integer.toString(age));
}
JodaTime is simpler, however...
You need to loop from the start time to the end, incrementing the MONTH field on each loop while the date remains before the end time...
For example...
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal1 = Calendar.getInstance();
cal1.setTime(sdf.parse("08/03/1972"));
Calendar cal2 = Calendar.getInstance();
cal2.setTime(sdf.parse("08/03/2014"));
// Yes, you can use cal1, but I you might want
// to preserve it for other reasons...
Calendar cal3 = Calendar.getInstance();
cal3.setTime(cal1.getTime());
int months = 0;
while (cal3.before(cal2)) {
cal3.add(Calendar.MONTH, 1);
months++;
}
System.out.println("Months = " + months);
} catch (ParseException exp) {
exp.printStackTrace();
}
Prints out Months = 505.
If you change cal2 to 08/04/1972, it will print Months = 1
I've written this simple method to give me the date of every pay period and it has ceased to work as of January first. I'm really not sure what's wrong here. It doesn't return anything.
public static List<Date> getPayPeriodDatesSinceStartOfYear() {
Calendar cal = new GregorianCalendar();
cal.add(Calendar.WEEK_OF_YEAR, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.WEEK_OF_YEAR, 2);
Calendar currentDate = new GregorianCalendar();
currentDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
int counter = 2;
List<Date> dates = new ArrayList<Date>();
while ((cal.getTime().compareTo((currentDate.getTime())) <= 0)) {
dates.add(cal.getTime());
counter += 2;
cal.set(Calendar.WEEK_OF_YEAR, counter);
}
java.util.Collections.reverse(dates);
if(dates.isEmpty()){
JOptionPane.showMessageDialog(null, "NO DATES, SOMETHING IS WRONG!");
}
return dates;
}
Your while condition is not being met, the way you have it set up cal is greater than currentDate therefore the while loop never happens.
Calendar cal = new GregorianCalendar();
cal.add(Calendar.WEEK_OF_YEAR, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.WEEK_OF_YEAR, 2);
Why are you setting week to 1 and then to 2?
(cal.getTime().compareTo((currentDate.getTime())) <= 0)
See the doc for Date. It has methods like before(Date when) and after(Date when).