Java Calendar and Date Operations

Java – Find a given date belongs in which quarter:
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern(“MM/dd/yyyy”);
Calendar calendar = Calendar.getInstance();
Date processDate = sdf.parse(“4/10/2007”);
calendar.setTime(processDate);
Date date1 = calendar.getTime();
int quarter = TestDate.getQuarter(date1);
System.out.println(“Quarter for the date : “+sdf.format(calendar.getTime())+” is : “+quarter);
Prints the following Result :
Quarter for the date : 04/10/2007 is : 2

Java – Code for getQuarter() function:
public static int getQuarter(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int[] months = { 3, 6, 9, 12 };
int count = 0;
do {
calendar.set(year, months[count++], 1);
Date tempDt = calendar.getTime();
if(date.compareTo(tempDt)
return count;
} while(count
return 0;
}

Java – Find previous quarter begin and end dates for a given date:
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern(“MM/dd/yyyy”);
Calendar calendar = Calendar.getInstance();
Date processDate = sdf.parse(“4/10/2007”);
calendar.setTime(processDate);
Date date1 = calendar.getTime();
int quarter = TestDate.getQuarter(date1);
String currentQuarterBeginDate = “”;
String fromDt=””;
String toDt=””;
if ( quarter ==1){
currentQuarterBeginDate = “01/01/”+calendar.get(Calendar.YEAR);
}
if ( quarter ==2){
currentQuarterBeginDate = “04/01/”+calendar.get(Calendar.YEAR);
}
if ( quarter ==3){
currentQuarterBeginDate = “07/01/”+calendar.get(Calendar.YEAR);
}
if ( quarter ==4){
currentQuarterBeginDate = “10/01/”+calendar.get(Calendar.YEAR);
}
calendar.setTime(sdf.parse(currentQuarterBeginDate));
calendar.add(Calendar.MONTH, 3*-1);
fromDt = sdf.format(calendar.getTime());
String formmatedQuarterBeginDate = sdf.format(calendar.getTime());
calendar.setTime(new java.util.Date(formmatedQuarterBeginDate));
calendar.add(Calendar.MONTH, 3);
calendar.add(Calendar.DAY_OF_MONTH, -1);
toDt = sdf.format(calendar.getTime());
System.out.println(“Previous Quarter Begin Date : “+fromDt);
System.out.println(“Previous Quarter End Date : “+toDt);

Prints the following Result :
Previous Quarter Begin Date : 01/01/2007
Previous Quarter End Date : 03/31/2007

Java – Find previous Date for a given date:
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern(“MM/dd/yyyy”);
Calendar calendar = Calendar.getInstance();
Date processDate = sdf.parse(“4/10/2007”);
calendar.setTime(processDate);
calendar.add(Calendar.DAY_OF_MONTH, -1);
String previousDate = sdf.format(calendar.getTime());
System.out.println(“Previous Date is :”+previousDate);
Prints the following Result :
Previous Date is :04/09/2007

Java – Find previous Sunday for a given date:
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern(“MM/dd/yyyy”);
Calendar calendar = Calendar.getInstance();
Date processDate = sdf.parse(“4/24/2007”);
calendar.setTime(processDate);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
calendar.add(Calendar.DAY_OF_MONTH,-1*(dayOfWeek-1));
calendar.setTime(calendar.getTime());
String endDt = sdf.format(calendar.getTime());
System.out.println(“Previous Sunday is :”+endDt);
Prints the following Result :
Previous Sunday is :04/22/2007

Enjoy!!!!

12 Responses to “Java Calendar and Date Operations”

  • Josh Martin:

    Just thought I’d share a slightly different approach that is class-based and will return the start/end dates of a given quarter. Note it’s written in Groovy.

    Josh

    —————–

    import static java.util.Calendar.*

    class Quarter {

    Date date
    Date start
    Date end
    int monthInQuarter

    Quarter() {
    this.date = new Date()
    init()
    }

    Quarter(Date date) {
    this.date = date
    init()
    }

    Quarter getNext() {
    Calendar c = Calendar.getInstance()
    c.time = end
    c.add(DATE, 7)
    return new Quarter(c.time)
    }

    Quarter getPrevious() {
    Calendar c = Calendar.getInstance()
    c.time = start
    c.add(DATE, -7)
    return new Quarter(c.time)
    }

    private void init() {
    Calendar c = Calendar.getInstance()
    c.time = date
    int month = c.get(MONTH) + 1 // java uses 0-11 notation
    monthInQuarter = month % 3
    monthInQuarter = (monthInQuarter == 0) ? 3 : monthInQuarter
    calculateStart()
    calculateEnd()
    }

    private void calculateStart() {
    Calendar c = Calendar.getInstance()
    c.time = date
    c.add(MONTH, (1 – monthInQuarter))
    c.set(DATE, 1)
    c.set(HOUR_OF_DAY, 0)
    c.set(MINUTE, 0)
    c.set(SECOND, 0)
    c.set(MILLISECOND, 0)
    start = c.time
    }

    private void calculateEnd() {
    Calendar c = Calendar.getInstance()
    c.time = date
    c.add(MONTH, (3 – monthInQuarter))
    c.set(DATE, c.getActualMaximum(Calendar.DATE))
    c.set(HOUR_OF_DAY, 23)
    c.set(MINUTE, 59)
    c.set(SECOND, 59)
    c.set(MILLISECOND, 999)
    end = c.time
    }

    String toString() {
    String pattern = ‘(%1$tm-%1$td-%1$tY) %2$tm-%2$td-%2$tY – %3$tm-%3$td-%3$tY’
    return String.format(pattern, date, start, end)
    }

    }

  • Ed:

    Hi,

    just to share another version of getQuarter(Date date):
    public static int getQuarter(Date date)
    {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    return (calendar.get(Calendar.MONTH) + 3) / 3;
    }

    find begin and end dates of the previous quarter:
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MONTH, -1 – (cal.get(Calendar.MONTH) % 3));
    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));
    System.out.println(sdf.format(cal.getTime()));

    Calendar cal2 = Calendar.getInstance();
    cal2.add(Calendar.MONTH, -3 – (cal2.get(Calendar.MONTH) % 3));
    cal2.set(Calendar.DAY_OF_MONTH, 1);
    System.out.println(sdf.format(cal2.getTime()));

    find begin and end dates of the current quarter:
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MONTH, 2 – (cal.get(Calendar.MONTH) % 3));
    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));
    System.out.println(sdf.format(cal.getTime()));

    Calendar cal2 = Calendar.getInstance();
    cal2.add(Calendar.MONTH, 0 – (cal2.get(Calendar.MONTH) % 3));
    cal2.set(Calendar.DAY_OF_MONTH, 1);
    System.out.println(sdf.format(cal2.getTime()));

    find begin and end dates of the next quarter:
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MONTH, 5 – (cal.get(Calendar.MONTH) % 3));
    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));
    System.out.println(sdf.format(cal.getTime()));

    Calendar cal2 = Calendar.getInstance();
    cal2.add(Calendar.MONTH, 3 – (cal2.get(Calendar.MONTH) % 3));
    cal2.set(Calendar.DAY_OF_MONTH, 1);
    System.out.println(sdf.format(cal2.getTime()));

  • VM:

    Thanks for this article and Thanks Ed for sharing your approach.

  • Manuel Beck:

    @VM
    Perfect and simple getQuarter-Function. Thanks!

  • kannan:

    Precise and works well.thanks a lot

  • http://www.smelldelicious.com/v/vspfiles/templates/Perfume2/images/logos/dg.gif

    Hello Everybody

    During bday season when your searching for his & her special occasion womens presents you may need help finding the most current fragrances for your girlfriend, wife, husband or…just a special person. There is a simple solution for locating the top fragrances & birthday gifts – despite the fact that there are millions of colognes & perfumes on the list to potentially choose.

    http://www.SmellDelicious.com online store specializes in Men’s Gift Sets & has Lolita Lempicka & Swiss Alpine and thousands of additional womens fragrances.

    An example of our gift set perfumes & colognesA Superior decision for a special relative
    Jean Patou & Jean Paul Gaultier & Diane von Furstenberg & Diesel & Kenneth Cole & Kenzo & Leonard & Mary Kate and Ashley & Liz Claiborne & Kiss & Animale Parfums & Anna Sui & Bruno Banani & Burberry & Gendarme & Geoffrey Beene & Entre Filles & Erox & Joan Collins & Jockey International & Chantal Thomass & Charles Jourdan & Cacharel & Caesar’s World & Arrogance Mix & Ashanti & Hard Candy & Hasbro & Kenneth Cole & Kenzo & Parfums Morgan & Mexx & Krizia & MauboussinMax Azria.

    http://www.perfume.com/images/family_banners/fresh_men.jpg?1268443664

  • Nikstiep say: Same already discussed recently

    _____________
    vigara
    gernic
    0

  • alifali:

    i got problem here.how to write program using java to determines the numbers of days in a given semester.input to the program is the year,month and day information of the first and the last of semester.plez help me..

  • Hey guys want a java Date picker, any help!

  • Andy Hones:

    Nice example and it is really help me a lot to understand it.

    you can also get another date example on the following links.

    http://www.aoiblog.com/date-operation-in-java/
    http://www.aoiblog.com/java-date-operation-part-2/

  • Bindu:

    Hi how to find the difference between two give dates(basically in Timestamp)???
    example. if i enter first date as 18-08-2011(dd-mm-yyyy) and second date as
    17-09-2011(dd-mm-yyyy). so i want result as 30 days difference

  • How to get the calendar of a particular year………….
    for eg. if 2012…should get the calendar of 2012

Leave a Reply

*