简体   繁体   English

java下个月的最后一天

[英]java get last day in next month

I have variable nowDate type of Date and I want set variable nextDate contains last day in next month. 我有变量nowDate类型的日期,我想要设置变量nextDate包含下个月的最后一天。

For example: nowDate = 2013-04-16 例如:nowDate = 2013-04-16

So nextDate will contains 2013-05-31 所以nextDate将包含2013-05-31

How can I do that? 我怎样才能做到这一点?

Similar to Xavi but one less line of code :-) 类似于Xavi,但少了一行代码:-)

Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));

Try 尝试

private static Date getNextDate(Date nowDate) {
    Calendar c = Calendar.getInstance();
    c.setTime(nowDate);
    c.add(Calendar.MONTH, 1);
    c.set(Calendar.DATE, c.getMaximum(Calendar.DATE));
    Date nextDate = c.getTime();
    return nextDate;
}

Usage: 用法:

    Date nowDate = new Date();
    Date nextDate = getNextDate(nowDate);

You could try setting a Calendar to day one two months ahead, and then substract one day: 您可以尝试将Calendar设置为提前两个月的日期,然后减去一天:

Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 2);
c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.DATE, -1);
Date nextDate = c.getTime();

As others have already pointed out, you could also just add one month, and use Calendar.getActualMaximum() to set the last day of the following month. 正如其他人已经指出的那样,您也可以添加一个月,并使用Calendar.getActualMaximum()来设置下个月的最后一天。

Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 1);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextDate = c.getTime();

Using joda and cribbing off sinarf : 使用jodacriarf sinarf

DateTime dt = new DateTime().plusMonths(1);
DateTime lastJoda = dt.dayOfMonth().withMaximumValue();
Date last = lastJoda.toDate();
System.out.println(last.toString());

One way is to increment 2 months to your current month and set the date as 1st. 一种方法是将当月增加2个月并将日期设置为第1个月。 After that decrement the date by 1 and it will give you the last day of month. 之后,将日期减1,它将为您提供月中的最后一天。 This will automatically take care of leap year, 30 days, 31 days, 29 days and 28 days months. 这将自动处理闰年,30天,31天,29天和28天月。 Program below 以下计划

public class LastDayofNextMonth {

    public static void main(String args[])
    {

        Calendar cal = Calendar.getInstance();
        cal.set(2013,Calendar.APRIL, 14) ;
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+2);
        cal.set(Calendar.DATE,1);
        cal.add(Calendar.DATE,-1);
        System.out.println(cal.getTime().toString());

    }
}

tl;dr TL;博士

Very easy. 很容易。

YearMonth.now()            // Get entire month for the date current in the JVM’s current default time zone. Better to pass explicitly your desired/expected time zone.
         .plusMonths( 1 )  // Move to the following month.
         .atEndOfMonth()   // Returns a `LocalDate` object, for a date-only value without time-of-day and without time zone.
         .toString()       // Generate a String in standard ISO 8601 format.

2018-02-28 2018年2月28日

java.time java.time

The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes. 现代方法使用java.time类来取代麻烦的旧遗留日期时间类。

Get the date. 得到日期。

LocalDate today = LocalDate.now();

Better to pass explicitly the desired/expected time zone. 最好明确传递所需/预期的时区。

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;

Pull the YearMonth from that, to represent the month as a whole. YearMonth拉出YearMonth ,以表示整个月份。

YearMonth ym = YearMonth.from( today ) ;

Or skip the LocalDate entirely. 或完全跳过LocalDate

YearMonth ym = YearMonth.now( ZoneId.of( "America/Montreal" ) ) ;

Move to next month. 搬到下个月。

YearMonth ymNext = ym.plusMonths( 1 ) ;

Get the date at end of the month. 获取月末的日期。

LocalDate ld = ymNext.atEndOfMonth() ;

Generate a String in standard ISO 8601 format: YYYY-MM-DD. 生成标准ISO 8601格式的字符串:YYYY-MM-DD。

String output = ld.toString() ;

For other formats, search Stack Overflow for DateTimeFormatter class. 对于其他格式,请搜索DateTimeFormatter类的Stack Overflow。


About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . 这些类取代了麻烦的旧遗留日期时间类,如java.util.DateCalendarSimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参阅Oracle教程 And search Stack Overflow for many examples and explanations. 并搜索Stack Overflow以获取许多示例和解释。 Specification is JSR 310 . 规范是JSR 310

You may exchange java.time objects directly with your database. 您可以直接与数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later. 使用符合JDBC 4.2或更高版本的JDBC驱动程序 No need for strings, no need for java.sql.* classes. 不需要字符串,不需要java.sql.*类。

Where to obtain the java.time classes? 从哪里获取java.time类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目是未来可能添加到java.time的试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

Use Calendar : 使用日历

First Set the Calendar to the next month. 首先将日历设置为下个月。 Use: cal.add(Calendar.MONTH, 1); 使用: cal.add(Calendar.MONTH, 1);

Then Use getActualMaximum to calculate the last day of the month that you set in previous step. 然后使用getActualMaximum计算您在上一步中设置的月份的最后一天。

import java.util.Calendar; 
import java.util.Date;

public class Main{

    public static void main(String ar[]){
        Calendar cal = Calendar.getInstance();

        cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
        cal.add(Calendar.MONTH, 1);
        Date lastDateOfNextMonth = cal.getTime();
        System.out.println(lastDateOfNextMonth ); 

    }
}

IDEONE DEMO IDEONE DEMO

we have so many good answers, however all above answers have code like: 我们有很多好的答案,但上面的所有答案都有如下代码:

cal.add(Calendar.MONTH, 1);

this code produce a little confusion because Months start at 0, so 1 is for February. 这段代码会产生一些混乱,因为Months从0开始,所以1代表2月。

(Edit: The integer in the add() function is not the month number (1=february) but the number of months to add ) (编辑:add()函数中的整数不是月份数(1 = 2月),而是要添加的月数)

You can do the following to get last day of month 您可以执行以下操作以获取每月的最后一天

Calendar calendar = Calendar.getInstance();   
calendar.setTime(date);   
calendar.getActualMaximum(Calendar.DAY_OF_MONTH);   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM