Java 如果当前月份是二月,如何获得下个月的开始日期和结束日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23493196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:23:48  来源:igfitidea点击:

How to get next month start date and end date if current month is february?

javadate

提问by Sankar

   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 .

上面的代码是我的输入,我需要“03/01/2014”和“03/31/2014”作为输出。我尝试了更多代码并使用了日历功能,但没有结果。从这个程序我需要下个月的开始和结束日期。

    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

我尝试了更多的示例输入,对于 2 月、4 月、6 月 11 月的开始日期,如果我将这些日期作为输入传递,它会在下个月的 2 日返回,建议任何想法进一步进行。我正在努力处理这段代码。提前致谢

采纳答案by ZahiC

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();

回答by niiraj874u

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

因为很难进入你的代码,所以我为你写了一些 coe。请检查一下..

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));

回答by Vinay Rao

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);

回答by Basil Bourque

tl;dr

tl;博士

LocalDate.parse( "02/14/2014" , DateTimeformatter.ofPattern( "MM/dd/uuuu" ) )
         .with( TemporalAdjusters.firstDayOfNextMonth() )  // Stop here for first of next month.
         .with( TemporalAdjusters.lastDayOfMonth() )  // Include this for last day of next month.

java.time

时间

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

现代方法是使用与 Java 8 捆绑的新java.time 包(受 Joda-Time 启发,由 JSR 310 定义)。

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

LocalDate级表示没有时间一天和不同时区的日期,唯一的价值。

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

The TemporalAdjusterinterface defines a way for implementations to manipulate date-time values. The TemporalAdjustersclass provides several handy implementations.

TemporalAdjuster接口定义了一种操作日期时间值的实现方式。本TemporalAdjusters类提供了一些方便的实现。

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 notincluding, 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-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

更新:现在处于维护模式Joda-Time项目建议迁移到java.time类。

Easy when using the Joda-Timelibrary and its LocalDateclass.

使用Joda-Time库及其LocalDate类时很容易。

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 nextmonth.

在半开中,开头是包容的,结尾是排斥的。因此,对于“一个月”,我们先从第一所期望的一个月,运行到,但不包括,第一个的下一个月份。

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.

请注意,Joda-Time 提供了三个方便的类来处理时间跨度:IntervalPeriodDuration

These classes work only with date-time objects (DateTimeclass) rather than the date-only (LocalDateclass) shown in code above.

这些类仅适用于日期时间对象 ( DateTimeclass) 而不是LocalDate上面代码中显示的仅日期 ( class)。

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

虽然与您的问题没有直接关系,但我怀疑这些时间跨度的课程可能会有所帮助。



About java.time

关于java.time

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

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

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

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

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

您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject 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.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多

回答by Philip John

I see the question is old. But I used the DateUtilsstatic methods ceilingand truncate. Came in pretty handy instead of using multiple lines of code.

我看到这个问题很老了。但是我使用了DateUtils静态方法天花板截断。非常方便,而不是使用多行代码。

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