lamwaiman1988 lamwaiman1988 - 1 year ago 84
Java Question

How to identify date of 6 complete months ago

I need to identify the date which is 6 complete months ago. For example:

Feb-27, 2012(Today) - It is Feb and we don't count incomplete month, false
Feb-01, 2012 - Still Feb so don't count too, false
Jan-01, 2011 - Completed, false
Dec-01, 2011 - Completed, false
Nov-01, 2011 - Completed, false
Oct-01, 2011 - Completed, false
Sep-01, 2011 - Completed, false
Aug-01, 2011 - Completed, false
Jul-01, 2011 - Already pass 6 complete months, true

It should work in whatever date in the future.

I thought of current date minus 30*6=180 days, but it is not accurate.

It needs to be accurate because, for example, if we identify Jul 2011 is valid then we will housekeep all the data for that month.


Answer Source

If you could use JodaTime, here is code for ±6 months calculation:

    import org.joda.time.DateTime;
    import org.joda.time.Months;
    DateTime now = new DateTime();
    DateTime then = new DateTime().withDate(2011, 8, 1);
    if(Math.abs(Months.monthsBetween(now, then).getMonths()) > 6){
        System.out.println("6 mo apart!");
        //your logic goes here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download