8
   String febSt = "02/01/2014" ;
   String febEnd = "02/28/2014" ;

Above code is my input i need "03/01/2014" and "03/31/2014" as output . I tried more codes and used calendar functions also but no result.From this program i need next month start and end date .

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

    public class MonthCalculation {


        public void getNextMonth(String date) throws ParseException{


            DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
            Date dt = format.parse(date);


            Date begining, end;

            {
                Calendar calendar = getCalendarForNow(dt);
                calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
                setTimeToEndofDay(calendar);
                end = calendar.getTime();

                SimpleDateFormat endDt = new SimpleDateFormat("MM/dd/yyyy");
                String endStrDt = endDt.format(end);
                if(date != null && date.equalsIgnoreCase(endStrDt)){
                    System.out.println("Ending of the month");
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    Date lastDate = calendar.getTime();
                    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
                    String lastDateofNextMonth = sdf.format(lastDate);
                    System.out.println("Next Month :"+lastDateofNextMonth);

                    Calendar c = getCalendarForNow(new Date(lastDateofNextMonth));
                    calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
                    setTimeToEndofDay(calendar);
                    end = calendar.getTime();

                    SimpleDateFormat sfd = new SimpleDateFormat("MM/dd/yyyy");
                    String lastDated = endDt.format(end);
                    System.out.println("Testing side :"+lastDated);

                }else if (findLeapYear(dt)){
                    Calendar calendar3 = getCalendarForNow(dt);
                    calendar3.add(Calendar.YEAR, 1);
                    Date ds = calendar3.getTime();
                    SimpleDateFormat dtft = new SimpleDateFormat("MM/dd/yyyy");
                    String dates = dtft.format(ds);
                    dtft.setLenient(false);
                    System.out.println("YEAR : "+dates);

                }else{
                                    SimpleDateFormat dtft = new SimpleDateFormat("MM/dd/yyyy");
                    Calendar calendar2 = getCalendarForNow(dt);
                    System.out.println(" Calendar time :->> " + dtft.format(calendar2.getTime()));
                    int curre_month = calendar2.get(Calendar.MONTH);
                    int curre_day = calendar2.get(Calendar.DAY_OF_MONTH);
                    int curre_year = calendar2.get(Calendar.YEAR);

                    Date dat = calendar2.getTime();
                    calendar2.add(Calendar.DATE, 31);
                    Date ds = calendar2.getTime();
                    String dates = dtft.format(ds);
                    dtft.setLenient(false);
                    System.out.println("OTHER DAYS : "+dates);

                }
            }

        }

        private static boolean findLeapYear(Date dt){
            boolean isLeapYr = false;
            int yr = dt.getYear();
            if ((yr%4 == 0 && yr%100!=0)){
                isLeapYr = true;
               }
            return isLeapYr;
        }

        private static Calendar getCalendarForNow(Date dt) {
            Calendar calendar = GregorianCalendar.getInstance();
            calendar.setTime(dt);
            return calendar;
        }

        private static void setTimeToBeginningOfDay(Calendar calendar) {
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
        }

        private static void setTimeToEndofDay(Calendar calendar) {
            System.out.println("For feb calling");
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MILLISECOND, 999);
        }


        public static void main(String[] args) {

            try {
                String janSt = "01/01/2014" ;
                    String janEnd = "01/31/2014" ;

                    String febSt = "02/01/2014" ;
                    String febEnd = "02/28/2014" ;

                    String marSt = "03/01/2014" ;
                    String marEnd = "03/31/2014" ;

                    String aprilSt = "04/01/2014" ;
                    String aprilEnd = "04/30/2014" ;

                    String maySt = "05/01/2014" ;
                    String mayEnd = "05/31/2014" ;

                    String juneSt = "06/01/2014" ;
                    String juneEnd = "06/30/2014" ;

                    String julySt = "07/01/2014" ;
                    String julyEnd = "07/31/2014" ;

                    String augSt = "08/01/2014" ;
                    String augEnd = "08/31/2014" ;

                    String sepSt = "09/01/2014" ;
                    String sepEnd = "09/30/2014" ;

                    String octSt = "10/01/2014" ;
                    String octEnd = "10/31/2014" ;

                    String novSt = "11/01/2014" ;
                    String novEnd = "11/30/2014" ;

                    String deceSt = "12/01/2014" ;
                    String deceEnd = "12/31/2014" ;

                    String jan15St="01/01/2015";
                    String jan15End="01/31/2015";

                    String leapyr = "02/29/2016";
                    String notaleapyr = "02/28/2015";

                new MonthCalculation().getNextMonth(febSt);
            } catch (ParseException e) {
                e.printStackTrace();
            }


        }

I tried more with sample inputs , for the months February ,april, june nov start date are not working if i pass these dates as inputs it returns with 2nd of next month Suggest any idea to proceed further.I am struggling this code. Thanks in advance

Sankar
  • 131
  • 1
  • 2
  • 11
  • 4
    Post your code that didnt work – Reimeus May 06 '14 at 11:17
  • I think the quickest is to find the first day of the month being March and add -1 day , but again that's a little hacky – Kenneth Clark May 06 '14 at 11:25
  • 2
    Or Joda Time? That would definitely be better than using Date/Calendar. – Jon Skeet May 06 '14 at 11:25
  • 1
    I'd also *strongly* advise you to separate out your text conversion code from the date handling code. Currently they're mixed up all over the place - it would be much cleaner if you had a parse phase, a processing phase, and then a formatting phase. Then you could have a separate method for each, which didn't need to care about anything else. – Jon Skeet May 06 '14 at 11:27
  • If we add -1 day mean for march month start and end date if i pass then i wont get a next(April) months start and end date it displays wrong output. – Sankar May 06 '14 at 11:27

5 Answers5

32

Try this:

Calendar calendar = Calendar.getInstance();         
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date nextMonthFirstDay = calendar.getTime();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextMonthLastDay = calendar.getTime();
ZahiC
  • 13,567
  • 3
  • 25
  • 27
9

tl;dr

LocalDate.parse( "02/14/2014" , DateTimeformatter.ofPattern( "MM/dd/uuuu" ) )
         .with( TemporalAdjusters.firstDayOfNextMonth() )  

…and…

LocalDate.parse( "02/14/2014" , DateTimeformatter.ofPattern( "MM/dd/uuuu" ) )
         .with( TemporalAdjusters.lastDayOfMonth() )  

java.time

The modern way is with the new java.time package bundled with Java 8 (inspired by Joda-Time, defined by JSR 310).

The LocalDate class represents a date-only value without time-of-day and without time zone.

DateTimeFormatter f = DateTimeformatter.ofPattern( "MM/dd/uuuu" );
LocalDate ld = LocalDate.parse( "02/14/2014" , f );

The TemporalAdjuster interface defines a way for implementations to manipulate date-time values. The TemporalAdjusters class provides several handy implementations.

LocalDate firstOfMonth = ld.with( TemporalAdjusters.firstDayOfMonth() );
LocalDate firstOfNextMonth = ld.with( TemporalAdjusters.firstDayOfNextMonth() );

The Question asks for the first and last of the following month, March in this case. We have the first of next month, so we just need the end of that month.

LocalDate lastOfNextMonth = firstOfNextMonth.with( TemporalAdjusters.lastDayOfMonth() );

By the way, as discussed below, the best practice for defining a span of time is the Half-Open approach. That means a month is the first of the month and running up to, but not including, the first of the month after. In this approach we do not bother with determining the last day of the month.

Joda-Time

UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

Easy when using the Joda-Time library and its LocalDate class.

DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy" );
LocalDate localDate = formatter.parseLocalDate( "02/14/2014" ); 
LocalDate firstOfMonth = localDate.withDayOfMonth( 1 ); 
LocalDate nextMonth = localDate.plusMonths(1); // Use this for "half-open" range.
LocalDate endOfMonth = nextMonth.minusDays(1); // Use this for "fully-closed" range.

Half-Open

Tip: Rather than focus on the last moment of a span of time, a better practice is to use the "Half-Open" approach.

In half-open, the beginning is inclusive and the ending is exclusive. So for "a month", we start with the first of the desired month and run up to, but not including, the first of the next month.

February 2014 = 2014-02-01/2014-03-01

Span Of Time

Be aware that Joda-Time provides three handy classes for handling a span of time: Interval, Period, and Duration.

These classes work only with date-time objects (DateTime class) rather than the date-only (LocalDate class) shown in code above.

While not directly relevant to your question, I suspect these span-of-time classes may be helpful.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
3

Something I quickly wrote for you - so could be cleaned up. Check if this helps:

    String string = "02/01/2014"; //assuming input
    DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    Date dt = sdf .parse(string);
    Calendar c = Calendar.getInstance();
    c.setTime(dt);
    c.add(Calendar.MONTH, 1);  //adding a month directly - gives the start of next month.
    String firstDate = sdf.format(c.getTime());
    System.out.println(firstDate);

    //get last day of the month - add month, substract a day.
    c.add(Calendar.MONTH, 1);
    c.add(Calendar.DAY_OF_MONTH, -1);
    String lastDate = sdf.format(c.getTime());
    System.out.println(lastDate);
Vinay Rao
  • 1,284
  • 9
  • 13
  • Hi Vinay Rao , My input is if i pass month start and end date means it should return next month start and end-date respectively ,this what i wrote above the code .From your program it returns current month start and end date but i need next month start and enddate . – Sankar May 06 '14 at 12:03
  • Sankar, that's what it does - it takes 1-Feb and returns 1-Mar and 31-Mar. That's what you need, right? I am adding a month. – Vinay Rao May 07 '14 at 06:23
  • Ok i agree this is for month shifting , in case if i shift one year means what to do .Suppose shifted year was leap year then i need that month Feb 28 .Eg:-Input 02/29/2016 , output -02/28/2017.Another one Input--- 02/28/2015 i need a output 02/29/2016 ,for these cases what to do ...? – Sankar May 07 '14 at 09:28
  • This is applicable for all 12 months.If i pass Eg:-Input 02/21/2014 , output -02/22/2014 and Eg2:-Input 04/16/2015 , output -05/16/2015 respectively. – Sankar May 07 '14 at 10:32
  • Okay, so your input need not be the 1st of every month. You need to polish your question. Anyway, you can use the Calendar class to your advantage. Force the day of month to the the last day of month. I'd probably reset day of month to 1, add the year, and then set the date to last day of month. Let me know if you want me to post the code. – Vinay Rao May 08 '14 at 07:40
  • Thanks for your response.I tried more,but i cant find the solution.My requirement is if i pass month start date, end-date or in-between days i want next month start date or end date or in-between days .It also applicable for years also .Suppose if that year is leap year means i for month February i want last date (29th-Feb).Just provide the code for that one. – Sankar May 09 '14 at 09:29
2

since it is hard to get in your code I have write some coe for you. please check it out..

Date today = new Date();  

Calendar calendar = Calendar.getInstance();  
calendar.setTime(today);  

calendar.add(Calendar.MONTH, 1);  
calendar.set(Calendar.DAY_OF_MONTH, 1);  
calendar.add(Calendar.DATE, -1);  

Date lastDayOfMonth = calendar.getTime();  

DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");  
System.out.println("Today            : " + sdf.format(today));  
System.out.println("Last Day of Month: " + sdf.format(lastDayOfMonth));
niiraj874u
  • 2,180
  • 1
  • 12
  • 19
  • niiraj874u,My input is if i pass month start and end date means it should return next month start and end-date respectively ,this what i wrote above the code . – Sankar May 06 '14 at 11:38
2

I see the question is old. But I used the DateUtils static methods ceiling and truncate. Came in pretty handy instead of using multiple lines of code.

Date today = new Date();

DateUtils.truncate(new Date(), Calendar.MONTH) // Thu Dec 01 00:00:00 EET 2016
DateUtils.ceiling(new Date(), Calendar.MONTH) // Sun Jan 01 00:00:00 EET 2017
Philip John
  • 5,275
  • 10
  • 43
  • 68