Wednesday, March 21, 2012

How To Get Date Range in Java Calendar's set() add() and roll()

0 comments

 Calendar (Java 2 Platform SE 5.0) set() add()  and roll() 



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

/**
 *
 * @author JSupport http://javasrilankansupport.blogspot.com
 */

enum DateEnum {
    DAILY,
    WEEKLY,
    MONTHLY;
}

public class DateRange {

    public int x = 2;
    public String date,stdate,endate;

    private String getDateTime(DateEnum type) {

        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Date d = c.getTime();
        
        c.setTime(d);

        switch (type) {

            case DAILY:
                c.roll(Calendar.DAY_OF_WEEK, -1);
                date = sdf.format(c.getTime());
                break;
            case WEEKLY:
                 c.roll(Calendar.DAY_OF_WEEK, -1);
                 stdate = sdf.format(c.getTime());
                 c.roll(Calendar.WEEK_OF_MONTH,-1);
                 endate = sdf.format(c.getTime());
                 date = stdate+","+endate;
                break;

            case MONTHLY:
                 c.roll(Calendar.DAY_OF_WEEK, -1);
                 stdate = sdf.format(c.getTime());
                 c.roll(Calendar.MONTH,-1);
                 endate = sdf.format(c.getTime());
                 date = stdate+","+endate;
                break;
        }
        return date;
    }

    public static void main(String[] arr) {

        DateRange dr = new DateRange();

        System.out.println(dr.getDateTime(DateEnum.DAILY));
        System.out.println(dr.getDateTime(DateEnum.WEEKLY));
        System.out.print(dr.getDateTime(DateEnum.MONTHLY));

    }
}

0 comments:

Post a Comment