September 24, 2017

To Loop all dates between a start date and end date in java

/**
 *
 */
package com.belazy.misc;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.ReadableInstant;

/**
 * @author belazy
 *
 */
public class DateManipulation {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DateManipulation dateManip = new DateManipulation();
try {
dateManip.printDateBw("2017-10-01","2017-10-10");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

private void printDateBw(String startDate, String endDate) throws ParseException {

int days = Days.daysBetween(LocalDate.parse(startDate), LocalDate.parse(endDate)).getDays();
System.out.println(days);

SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
Date stDate = sd.parse(startDate);
System.out.println(" start date :"+stDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(startDate)); // parsed date and setting to calendar

for(int i=1;i<=days;i++){

calendar.add(Calendar.DATE, 1);  // number of days to add
String destDate = sd.format(calendar.getTime());  // End date
System.out.println(destDate);

}

}

}


program 2

/**
 *
 */
package com.belazy.misc;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.ReadableInstant;

/**
 * @author belazy
 *
 */
public class DateManipulation {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DateManipulation dateManip = new DateManipulation();
try {
dateManip.printDateBw("2017-10-01","2017-10-10");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

private void printDateBw(String startDate, String endDate) throws ParseException {

int days = Days.daysBetween(LocalDate.parse(startDate), LocalDate.parse(endDate)).getDays();
System.out.println(days);

SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
Date stDate = sd.parse(startDate);
System.out.println(" start date :"+stDate);
Calendar calendar = Calendar.getInstance();
// parsed date and setting to calendar

for(int i=0;i<days;i++){
calendar.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(startDate));
calendar.add(Calendar.DAY_OF_YEAR, i);  // number of days to add
String destDate = sd.format(calendar.getTime());  // End date
System.out.println(destDate);

}

}

}


No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments