java时间加5年,如何在Java中获取当前日期并添加五个工作日

I want two dates.

1) Current date in MM/dd/yy format

2) Modified date which will be the adition of five business days(Mon-Fri) to current date and it should be in MMM dd, yyyy format.

So if my current is 9th june than currentDate should be 06/09/14 and modifiedDate should be Jun 13, 2014.

How to do this?

解决方案

This will add working days (Mon-Fri) and will present dates in the required format.

UPDATED 6 Jul 2020

Now custom days can be used as non working days (see the list NON_BUSINESS_DAYS)

Now even the past date can be calculated as well (set businessDays as negative val)

import java.text.SimpleDateFormat;

import java.util.Arrays;

import java.util.Calendar;

import java.util.Date;

import java.util.List;

public class BusinessDateExamples {

private static final List NON_BUSINESS_DAYS = Arrays.asList(

Calendar.SATURDAY,

Calendar.SUNDAY

);

/**

* Returns past or future business date

* @param date starting date

* @param businessDays number of business days to add/subtract

*
note: set this as negative value to get past date

* @return past or future business date by the number of businessDays value

*/

public static Date businessDaysFrom(Date date, int businessDays) {

Calendar calendar = Calendar.getInstance();

calendar.setTime(date);

for (int i = 0; i < Math.abs(businessDays);) {

// here, all days are added/subtracted

calendar.add(Calendar.DAY_OF_MONTH, businessDays > 0 ? 1 : -1);

// but at the end it goes to the correct week day.

// because i is only increased if it is a week day

if (!NON_BUSINESS_DAYS.contains(calendar.get(Calendar.DAY_OF_WEEK))){

i++;

}

}

return calendar.getTime();

}

public static void main(String...strings) {

SimpleDateFormat s = new SimpleDateFormat("MM/dd/yy ( MMM dd, yyyy )");

Date date = new Date();

int businessDays = 5;

System.out.println(s.format(date));

System.out.print("+ " + businessDays + " Business Days = ");

System.out.println(s.format(businessDaysFrom(date, businessDays)));

System.out.print("- " + businessDays + " Business Days = ");

System.out.println(s.format(businessDaysFrom(date, -1 * businessDays)));

}

}

Date date=new Date();

Calendar calendar = Calendar.getInstance();

date=calendar.getTime();

SimpleDateFormat s;

s=new SimpleDateFormat("MM/dd/yy");

System.out.println(s.format(date));

int days = 5;

for(int i=0;i

{

calendar.add(Calendar.DAY_OF_MONTH, 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(calendar.get(Calendar.DAY_OF_WEEK)<=5)

{

i++;

}

}

date=calendar.getTime();

s=new SimpleDateFormat("MMM dd, yyyy");

System.out.println(s.format(date));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值