Java 获取本月的最后一天

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19488658/
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-12 17:41:48  来源:igfitidea点击:

Get last day of Month

javadatecalendar

提问by Anurag Tripathi

For getting last date of month I have written this function

为了获得月份的最后一天,我编写了这个函数

/**
 * @param month integer value of month
 * @param year integer value of month
 * @return last day of month in MM/dd/YYYY format
 */
private static String getDate(int month, int year) {
    Calendar calendar = Calendar.getInstance();
    // passing month-1 because 0-->jan, 1-->feb... 11-->dec
    calendar.set(year, month - 1, 1);
    calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
    Date date = calendar.getTime();
    DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/YYYY");
    return DATE_FORMAT.format(date);
}

for all the inputs its working fine with one exception when the month is December, i.e. getDate(12, 2012) returns 12/31/2013 but it should return 12/31/2012. Please explain the behavior and solution too.

对于所有输入,其工作正常,但有一个例外,即当月是 12 月时,即 getDate(12, 2012) 返回 12/31/2013,但它应该返回 12/31/2012。请解释行为和解决方案。

采纳答案by rohan kamat

Change YYYYto yyyy

更改YYYYyyyy

DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy");  

YYYYis wrong dateformat

YYYY是错的 dateformat

回答by Scary Wombat

Try this

尝试这个

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

Date date = calendar.getTime();

回答by Elton Wang

private static String getDate(int month, int year) {
    Calendar calendar = Calendar.getInstance();

    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));

    Date date = calendar.getTime();
    DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy");
    return DATE_FORMAT.format(date);
}

回答by Oussama Zoghlami

Try to use Joda-Time, it's more simple :

尝试使用Joda-Time,它更简单:

private static String getLastDayOfMonth(int month, int year) {
    LocalDate lastDayOfMonth = new LocalDate(year, month, 1).dayOfMonth().withMaximumValue();
    return lastDayOfMonth.toString("MM/dd/yyyy");
}

回答by parag.rane

Try this

尝试这个

private static String getDate(int month, int year)
{
    Calendar dateCal = Calendar.getInstance();
    dateCal.set(year, month, 2);
    int maxDay = dateCal.getActualMaximum(Calendar.DAY_OF_MONTH);

    String pattern = "MMMM";
    SimpleDateFormat obDateFormat = new SimpleDateFormat(pattern);
    String monthName = obDateFormat.format(dateCal.getTime());

    return "Last date of " + monthName + " " + year + " : " + maxDay;
}

回答by Zeeshan

With Java 8 DateTime / LocalDateTime :

private static String getDate(int month, int year) {        
    Month monthObj = Month.of(month);       
    LocalDate date = LocalDate.of(year, month, monthObj.maxLength());
    return date.format(DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US));
}

回答by Tanmay kumar shaw

You can use the following code to get last day of the month

您可以使用以下代码获取本月的最后一天

public static String getLastDayOfTheMonth(String date) {
        String lastDayOfTheMonth = "";

        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
        try{
        java.util.Date dt= formatter.parse(date);
        Calendar calendar = Calendar.getInstance();  
        calendar.setTime(dt);  

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

        java.util.Date lastDay = calendar.getTime();  

        lastDayOfTheMonth = formatter.format(lastDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return lastDayOfTheMonth;
    }

回答by Basil Bourque

tl;dr

tl;博士

YearMonth.of( 2016 , 6 )
         .atEndOfMonth()
         .toString()

2016-06-30

2016-06-30

java.time

时间

Very easy with the java.timeclasses built into Java 8 and later. Back-ported to Java 6 & 7, and further adapted to Android.

使用Java 8 及更高版本中内置的java.time类非常容易。向后移植到 Java 6 & 7,并进一步适应 Android

YearMonth

YearMonth

Use the handy YearMonthclass.

使用方便的YearMonth类。

Tip: Pass objects of this class around your code base rather than mere integers to benefit from type-safety, guaranteed valid values, and more self-documenting code.

提示:在您的代码库周围传递此类的对象,而不仅仅是整数,以从类型安全、保证有效值和更多自文档化代码中受益。

YearMonth yearMonth = YearMonth.of( 2016 , 6 );

…or…

…或者…

YearMonth yearMonth = YearMonth.of( 2016 , Month.JUNE );

LocalDate

LocalDate

Then ask for the last day of that month, represented by LocalDate.

然后询问该月的最后一天,用 表示LocalDate

LocalDate endOfMonth = yearMonth.atEndOfMonth();

2016-06-30

2016-06-30

Strings

字符串

The result of toStringyou see above, where a String was generated using standard ISO 8601formatting. You can use other formatting.

toString您在上面看到的结果,其中使用标准ISO 8601格式生成字符串。您可以使用其他格式。

The DateTimeFormatterclass can automatically translate to a human language and apply cultural norms to issues such as period versus comma or the ordering of year-month-day parts.

DateTimeFormatter课程可以自动翻译成人类语言,并将文化规范应用于诸如句号与逗号或年-月-日部分的排序等问题。

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT );
formatter = formatter.withLocale( Locale.US );  // Re-assign JVM's current default Locale that was implicitly applied to the formatter.
String output = localDate.format( formatter ); 

The Locale.USgives us a month/day/year format. You can also specify an explicit pattern by calling DateTimeFormatter.ofPattern.

Locale.US给了我们一个月/日/年的格式。您还可以通过调用指定显式模式DateTimeFormatter.ofPattern

回答by Pranav

Are you considering leap year as well here? if not then you can try below code:

你也在考虑闰年吗?如果没有,那么您可以尝试以下代码:

public static Date calculateMonthEndDate(int month, int year) {
    int[] daysInAMonth = { 29, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    int day = daysInAMonth[month];
    boolean isLeapYear = new GregorianCalendar().isLeapYear(year);

    if (isLeapYear && month == 2) {
        day++;
    }
    GregorianCalendar gc = new GregorianCalendar(year, month - 1, day);
    Date monthEndDate = new Date(gc.getTime().getTime());
    return monthEndDate;
}