I want to get the dates in between the calendar, but for some reason this does not work. Any suggestions why? Thanks.
public boolean verifyDate(Calendar cal) {
Calendar toDate = Calendar.getInstance();
toDate.setTime(passToDate);
Calendar fromDate = Calendar.getInstance();
fromDate.setTime(passFromDate);
return !((fromDate.after(cal) && toDate.before(cal)) || DateUtils.isSameDay(fromDate, cal) || DateUtils.isSameDay(toDate, cal));
}
fromDate.after(cal) - will return true if fromDate will be after the cal, similar thing with before.
If you want to check that cal is between two dates use:
return cal.after(fromDate) && cal.before(toDate)
&& !(DateUtils.isSameDay(fromDate, cal) || DateUtils.isSameDay(toDate, cal));
public static List<String> getDates(String startDate, String endDate)
throws ParseException, java.text.ParseException {
List<String> dateList = new ArrayList<String>();
if (startDate == null || startDate.equals("") || endDate == null || endDate.equals("")) {
return null;
}
Calendar calendar = new GregorianCalendar();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = dateFormat.parse(startDate);
Date d2 = dateFormat.parse(endDate);
Calendar calendar2 = new GregorianCalendar();
calendar2.setTime(d2);
calendar2.add(Calendar.DATE, 1);
calendar.setTime(d1);
while (calendar.getTime().before(calendar2.getTime()))
{
Date result = calendar.getTime();
dateList.add(dateFormat.format(result));
calendar.add(Calendar.DATE, 1);
}
return dateList;
}
Related
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();
}
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 am getting actual date using this:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Calendar cal = Calendar.getInstance();
String today = dateFormat.format(cal.getTime());
System.out.println(today);
It prints today`s date: 21.04.2014
Then, I want to compare this date whether it is between two dates:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date actualdate = sdf.parse(today);
Date date1 = sdf.parse("20.04.2014");
Date date2 = sdf.parse("23.04.2014");
Calendar actual = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
actual.setTime(actualdate);
cal1.setTime(date1);
cal2.setTime(date2);
if(actual.after(date1) && actual.before(date2)) System.out.println("Yes");
else System.out.println("No");
It always prints No. What is the problem ? When I set date1 to 21.04.2014 and use actual.equals(date1) it works. But when I am using before or after it doesnt. Thanks
change it to actual.after(cal1) && actual.before(cal2)
you are comparing a calendar with dates
you must compare calendars with calendars or dates with dates
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Cal {
public static void main(String[] args) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy");
Calendar cal = Calendar.getInstance();
String today = dateFormat.format(cal.getTime());
System.out.println(today);
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
Date actualdate = sdf.parse(today);
Date date1 = sdf.parse("20042014");
Date date2 = sdf.parse("23042014");
Calendar actual = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
actual.setTime(actualdate);
cal1.setTime(date1);
cal2.setTime(date2);
System.out.println(actual);
System.out.println(cal1);
System.out.println(cal2);
if(actualdate.after(date1) && actualdate.before(date2)){
System.out.println("Yes");
}
else {
System.out.println("No");
}
if(actual.after(cal1) && actual.before(cal2)){
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}
I am sorry to tell you that the function that compares between two dates is useless and not working.
If you would like to have a go this is the function i tested
private static boolean validateEndDate(String startDate, String endDate)
{
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
Date date1 = dateFormat.parse(startDate);
Date date2 = dateFormat.parse(endDate);
if(date1.before(date2))
{
return true;
}
}catch(Exception e)
{
System.out.println(e.getMessage());
}
return false;
}
Now to see what i am talking about give it these two dates:
System.out.println(validateEndDate("31/07/2016","1/08/2016"));
Now to fix this problem i had to implement my own function:
private boolean compareDates(String startDate,String endDate)
{
int day=Integer.parseInt(startDate.split("/")[0]);
int month=Integer.parseInt(startDate.split("/")[1]);
int year=Integer.parseInt(startDate.split("/")[2]);
int day2=Integer.parseInt(endDate.split("/")[0]);
int month2=Integer.parseInt(endDate.split("/")[1]);
int year2=Integer.parseInt(endDate.split("/")[2]);
if(year<year2 || year==year2)
{
if(year<year2)
{
return true;
}
//Check the month
if(month<month2 || month==month2)
{
if(month<month2)
{
return true;
}
//Check the day
if(day<day2)
{
return true;
}
}
}
return false;
}
You are comparing Calender value with Date. Just use Date values. or just use Calender values. Don't mix them both.
actual.after(cal1) && actual.before(cal2)
or
actualdate.after(date1) && actualdate.before(date2)
see the working one:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date actual = sdf.parse("21.04.2014");
Date date1 = sdf.parse("20.04.2014");
Date date2 = sdf.parse("23.04.2014");
if(actual.after(date1) && actual.before(date2)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
hi all how to generate dates if the start date and end date are provided in java?
like the following :
Ex : if the start date is 15-04-2012 and end date is 15-06-2012 having this i want dates to be like the following and the list should omit saturday and sunday
1.15-04-2012,
2.16-04-2012,
3.17-04-2012,
.
.
.
.
.
.
15-06-2012
I have done like the following but it will generate for one month if the date range is of same month.
`
public static ConcurrentHashMap<String, String> getWorkingDaysMap(int year, int month, int day){
int totalworkingdays=0,noofdays=0;
String nameofday = "";
ConcurrentHashMap<String,String> workingDaysMap = new ConcurrentHashMap<String,String>();
Map<String,String> holyDayMap = new LinkedHashMap<String,String>();
noofdays = findNoOfDays(year,month,day);
for (int i = 1; i <= noofdays; i++) {
Date date = (new GregorianCalendar(year,month - 1, i)).getTime(); // year,month,day
SimpleDateFormat f = new SimpleDateFormat("EEEE");
nameofday = f.format(date);
String daystr="";
String monthstr="";
if(i<10)daystr="0";
if(month<10)monthstr="0";
String formatedDate = daystr+i+"/"+monthstr+month+"/"+year;
if(!(nameofday.equals("Saturday") || nameofday.equals("Sunday"))){
workingDaysMap.put(formatedDate,formatedDate);
totalworkingdays++;
}
}
return workingDaysMap;
}
So please do advice me how to go about.
Regards
Tony
int noOfDaysBetween = 5;
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
for(int index = 0 ; index < noOfDaysBetween; index++){
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if( dayOfWeek!=Calendar.SUNDAY && dayOfWeek!=Calendar.SATURDAY) {
System.out.println(cal.getTime());
}
cal.add(Calendar.DATE, 1);
}
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
//15-04-2012
calendar.set(Calendar.DAY_OF_MONTH, 15);
calendar.set(Calendar.YEAR, 2012);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MONTH, 3);
Date start = calendar.getTime();
//15-06-2012
calendar.set(Calendar.MONTH, 5);
Date end = calendar.getTime();
calendar.setTime(start);
Date d = null;
while((d = calendar.getTime()).before(end) || d.equals(end)) {
int day = calendar.get(Calendar.DAY_OF_WEEK);
if (day != Calendar.SATURDAY && day != Calendar.SUNDAY) {
System.out.println(d);
}
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
}
I prefer usage of LocalDate.
import java.time.DayOfWeek;
import java.time.LocalDate;
public class Game {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2018, 6, 1);
LocalDate end = LocalDate.of(2018, 8, 1);
LocalDate d = start;
while(d.compareTo(end) <= 0) {
if (d.getDayOfWeek() != DayOfWeek.SATURDAY && d.getDayOfWeek() != DayOfWeek.SUNDAY) {
System.out.println(d);
}
d = d.plusDays(1);
}
}
}
use the following joda-time
import org.joda.time.DateTimeConstants;
import org.joda.time.LocalDate;
public class DatesexcludingWeekend {
public static void main(String[] args) {
final LocalDate start = new LocalDate(2012, 06, 15);
final LocalDate end = new LocalDate(2012, 07, 14);
LocalDate weekday = start;
if (start.getDayOfWeek() == DateTimeConstants.SATURDAY|| start.getDayOfWeek() == DateTimeConstants.SUNDAY) {
weekday = weekday.plusWeeks(1).withDayOfWeek(DateTimeConstants.MONDAY);
}
while (weekday.isBefore(end)) {
System.out.println(weekday);
if (weekday.getDayOfWeek() == DateTimeConstants.FRIDAY)
weekday = weekday.plusDays(3);
else
weekday = weekday.plusDays(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).