Is it possible to add weekdays to joda time?
For instance, if current date is Friday 01/03, date + 1 should return Monday 04/03, rather than 02/03.
As far as I know there is no built-in method to automatically do this for you in Joda Time. However, you could write your own method, that increments the date in a loop until you get to a weekday.
Note that, depending on what you need it for exactly, this could be (much) more complicated than you think. For example, should it skip holidays too? Which days are holidays depends on which country you're in. Also, in some countries (for example, Arabic countries) the weekend is on Thursday and Friday, not Saturday and Sunday.
LocalDate newDate = new LocalDate();
int i=0;
while(i<days)//days == as many days as u want too
{
newDate = newDate.plusDays(1);//here even sat and sun are added
//but at the end it goes to the correct week day.
//because i is only increased if it is week day
if(newDate.getDayOfWeek()<=5)
{
i++;
}
}
System.out.println("new date"+newDate);
Be aware that iterating through adding N days one at a time can be relatively expensive. For small values of N and/or non performance sensitive code, this is probably not an issue. Where it is, I'd recommend minimizing the add operations by working out how many weeks and days you need to adjust by:
/**
* Returns the date that is {@code n} weekdays after the specified date.
* <p>
* Weekdays are Monday through Friday.
* <p>
* If {@code date} is a weekend, 1 weekday after is Monday.
*/
public static LocalDate weekdaysAfter(int n, LocalDate date) {
if (n == 0)
return date;
if (n < 0)
return weekdaysBefore(-n, date);
LocalDate newDate = date;
int dow = date.getDayOfWeek();
if (dow >= DateTimeConstants.SATURDAY) {
newDate = date.plusDays(8 - dow);
n--;
}
int nWeeks = n / 5;
int nDays = n % 5;
newDate = newDate.plusWeeks(nWeeks);
return ( (newDate.getDayOfWeek() + nDays) > DateTimeConstants.FRIDAY)
? newDate.plusDays(nDays + 2)
: newDate.plusDays(nDays);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With