Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify date of 6 complete months ago

Tags:

java

date

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.

Thanks.

like image 308
lamwaiman1988 Avatar asked Feb 27 '12 06:02

lamwaiman1988


2 Answers

I would try this simple logic to do the job.

Calendar cal = Calendar.getInstance();  //Get current date/month i.e 27 Feb, 2012
cal.add(Calendar.MONTH, -6);   //Go to date, 6 months ago 27 July, 2011
cal.set(Calendar.DAY_OF_MONTH, 1); //set date, to make it 1 July, 2011

Hope this helps.

like image 194
Ved Avatar answered Oct 13 '22 07:10

Ved


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
    }
like image 34
Nishant Avatar answered Oct 13 '22 08:10

Nishant