特定年份的特定月份的天数?


158

如何知道特定年份的特定月份有多少天?

String date = "2010-01-19";
String[] ymd = date.split("-");
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1]);
int day = Integer.parseInt(ymd[2]);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
int daysQty = calendar.getDaysNumber(); // Something like this

7
您到底是什么问题?
ShaMan-H_Fel 2012年

仅供参考,非常麻烦旧日期,时间类,如java.util.Datejava.util.Calendarjava.text.SimpleDateFormat现在的遗产,由取代java.time内置到Java 8和更高等级。请参见Oracle 教程
罗勒·布尔克

Answers:


368

Java 8及更高版本

@沃伦·诺科斯(Warren M. 如果您尝试使用Java 8的新Date and Time API,则可以使用java.time.YearMonthclass。请参见Oracle教程

// Get the number of days in that month
YearMonth yearMonthObject = YearMonth.of(1999, 2);
int daysInMonth = yearMonthObject.lengthOfMonth(); //28  

测试:尝试a年的一个月:

yearMonthObject = YearMonth.of(2000, 2);
daysInMonth = yearMonthObject.lengthOfMonth(); //29 

Java 7及更早版本

创建日历,设置年份和月份并使用 getActualMaximum

int iYear = 1999;
int iMonth = Calendar.FEBRUARY; // 1 (months begin with 0)
int iDay = 1;

// Create a calendar object and set year and month
Calendar mycal = new GregorianCalendar(iYear, iMonth, iDay);

// Get the number of days in that month
int daysInMonth = mycal.getActualMaximum(Calendar.DAY_OF_MONTH); // 28

测试:尝试a年的一个月:

mycal = new GregorianCalendar(2000, Calendar.FEBRUARY, 1);
daysInMonth= mycal.getActualMaximum(Calendar.DAY_OF_MONTH);      // 29

2
如何在Java 8的新Date and Time API上执行此操作?
沃伦·诺科斯

2
@ WarrenM.Nocos对您的迟到表示抱歉,但这些月我并不活跃。请检查该解决方案的修改对Java 8
与Hemant Metalia

对于Java 8之前的版本,在ThreeTen-Backport项目中,许多java.time功能都向后移植到Java 6和Java 7 。在ThreeTenABP项目中进一步适用于早期的Android 。请参阅如何使用ThreeTenABP…
罗勒·布尔克

43

java.util.Calendar的代码

如果您必须使用java.util.Calendar,我怀疑您想要:

int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

乔达时间代码

但是,就我个人而言,我建议您使用Joda Time而不是java.util.{Calendar, Date}开始使用,在这种情况下,您可以使用:

int days = chronology.dayOfMonth().getMaximumValue(date);

请注意,与其单独解析字符串值,不如获取用于解析它的日期/时间API更好。在java.util.*你可能使用SimpleDateFormat; 在Joda Time中,您将使用DateTimeFormatter


27

您可以使用Calendar.getActualMaximum方法:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
int numDays = calendar.getActualMaximum(Calendar.DATE);


7
if (month == 4 || month == 6 || month == 9 || month == 11)

daysInMonth = 30;

else 

if (month == 2) 

daysInMonth = (leapYear) ? 29 : 28;

else 

daysInMonth = 31;

日历c = Calendar.getInstance(); c.set(Calendar.DAY_OF_MONTH,c.getActualMaximum(Calendar.DAY_OF_MONTH)); //您可以设置年份,然后才能获得实际的最大Coz,它们可能会不同。即2011年和2012年2月的时长不一样(not年)
玫瑰

5

这是数学方法:

对于年,月(1到12):

int daysInMonth = month == 2 ? 
    28 + (year % 4 == 0 ? 1:0) - (year % 100 == 0 ? (year % 400 == 0 ? 0 : 1) : 0) :
    31 - (month-1) % 7 % 2;

3

我会寻求这样的解决方案:

int monthNr = getMonth();
final Month monthEnum = Month.of(monthNr);
int daysInMonth;
if (monthNr == 2) {
    int year = getYear();
    final boolean leapYear = IsoChronology.INSTANCE.isLeapYear(year);
    daysInMonth = monthEnum.length(leapYear);
} else {
    daysInMonth = monthEnum.maxLength();
}

如果月份不是2月(占案例的92%),则仅取决于月份,不涉及年份会更有效。这样,您不必调用逻辑即可知道这是否是a年,并且无需在92%的情况下获得年份。而且它仍然是干净且可读性强的代码。


1
我宁愿将整个逻辑留给经过验证的库方法-我认为您过早地进行了优化,而库方法并不是那么低效。仍然赞成使用现代的java.time。
Ole VV

@ OleV.V。的确,在许多情况下,将优化工作留给经过验证的库可能会更好。但是,在这种情况下,现有图书馆将需要经过一个月和一年。因此,这意味着即使该方法在92%的情况下都不会使用该值,我仍然需要尽一切努力来获得年份。因此,这是我无法优化的部分。我的推理与您不应执行方法调用以将值传递到可能已禁用的记录器的原因类似。记录器无法优化它。
Stefan Mondelaers

1

在Java8中,您可以从日期字段中使用get ValueRange。

LocalDateTime dateTime = LocalDateTime.now();

ChronoField chronoField = ChronoField.MONTH_OF_YEAR;
long max = dateTime.range(chronoField).getMaximum();

这使您可以在现场进行参数设置。


1

如此简单,无需导入任何内容

public static int getMonthDays(int month, int year) {
    int daysInMonth ;
    if (month == 4 || month == 6 || month == 9 || month == 11) {
        daysInMonth = 30;
    }
    else {
        if (month == 2) {
            daysInMonth = (year % 4 == 0) ? 29 : 28;
        } else {
            daysInMonth = 31;
        }
    }
    return daysInMonth;
}

如果您不需要历史日期或将来的日期,也可以。对于年份的二月,它是100的倍数,而不是400的倍数,这是错误的。但是我同意,在大多数应用程序中,这样做都是有效的。
Stefan Mondelaers

1
// 1 means Sunday ,2 means Monday .... 7 means Saturday
//month starts with 0 (January)

MonthDisplayHelper monthDisplayHelper = new MonthDisplayHelper(2019,4);
int numbeOfDaysInMonth = monthDisplayHelper.getNumberOfDaysInMonth();

1
值得注意的是,它适用于Android(android.util.MonthDisplayHelper
barbsan

0
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/*
 * 44. Return the number of days in a month
 * , where month and year are given as input.
 */
public class ex44 {
    public static void dateReturn(int m,int y)
    {
        int m1=m;
        int y1=y;
        String str=" "+ m1+"-"+y1;
        System.out.println(str);
        SimpleDateFormat sd=new SimpleDateFormat("MM-yyyy");

        try {
            Date d=sd.parse(str);
            System.out.println(d);
            Calendar c=Calendar.getInstance();
            c.setTime(d);
            System.out.println(c.getActualMaximum(Calendar.DAY_OF_MONTH));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public static void main(String[] args) {
dateReturn(2,2012);


    }

}

1
与现有和公认的答案相比,该答案提供什么价值?另外,请在代码中添加一些说明或叙述。StackOverflow不仅仅是一个片段库。
Basil Bourque 2014年

0
public class Main {

    private static LocalDate local=LocalDate.now();
    public static void main(String[] args) {

            int month=local.lengthOfMonth();
            System.out.println(month);

    }
}

6
还要添加一些说明。
BlackBeard

1
欢迎使用Stack Overflow!尽管此代码段可能是解决方案,但包括说明确实有助于提高您的帖子质量。请记住,您将来会为读者回答这个问题,而这些人可能不知道您提出代码建议的原因。
yivi '17

0

使用过时 Calendar应避免 API。

在Java8或更高版本中,可以使用 YearMonth

示例代码:

int year = 2011;
int month = 2;
YearMonth yearMonth = YearMonth.of(year, month);
int lengthOfMonth = yearMonth.lengthOfMonth();
System.out.println(lengthOfMonth);

Call requires API level 26 (current min is 21): java.time.YearMonth#lengthOfMonth
弗拉德

0

如果您不想对年份和月份的值进行硬编码,而又想从当前日期和时间中获取该值,则可以让它变得简单:

Date d = new Date();
String myDate = new SimpleDateFormat("dd/MM/yyyy").format(d);
int iDayFromDate = Integer.parseInt(myDate.substring(0, 2));
int iMonthFromDate = Integer.parseInt(myDate.substring(3, 5));
int iYearfromDate = Integer.parseInt(myDate.substring(6, 10));

YearMonth CurrentYear = YearMonth.of(iYearfromDate, iMonthFromDate);
int lengthOfCurrentMonth = CurrentYear.lengthOfMonth();
System.out.println("Total number of days in current month is " + lengthOfCurrentMonth );

0

您可以使用Calendar.getActualMaximum方法:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month-1);
int numDays = calendar.getActualMaximum(Calendar.DATE);

而month-1是因为月,因为它采用了它的原始月数,而在方法中,Calendar.class中的参数如下

public int getActualMaximum(int field) {
   throw new RuntimeException("Stub!");
}

并且(int字段)如下所示。

public static final int JANUARY = 0;
public static final int NOVEMBER = 10;
public static final int DECEMBER = 11;

0

以下方法将为您提供特定月份的天数

public static int getNoOfDaysInAMonth(String date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    return (cal.getActualMaximum(Calendar.DATE));
}

0

最佳的性能差异:

public static int daysInMonth(int month, int year) {
    if (month != 2) {
        return 31 - (month - 1) % 7 % 2;
    }
    else {
        if ((year & 3) == 0 && ((year % 25) != 0 || (year & 15) == 0)) { // leap year
            return 29;
        } else {
            return 28;
        }
    }
}

有关跳跃算法的更多详细信息,请点击此处


-1
String  MonthOfName = "";
int number_Of_DaysInMonth = 0;

//year,month
numberOfMonth(2018,11); // calling this method to assign values to the variables MonthOfName and number_Of_DaysInMonth 

System.out.print("Number Of Days: "+number_Of_DaysInMonth+"   name of the month: "+  MonthOfName );

public void numberOfMonth(int year, int month) {
    switch (month) {
        case 1:
            MonthOfName = "January";
            number_Of_DaysInMonth = 31;
            break;
        case 2:
            MonthOfName = "February";
            if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
                number_Of_DaysInMonth = 29;
            } else {
                number_Of_DaysInMonth = 28;
            }
            break;
        case 3:
            MonthOfName = "March";
            number_Of_DaysInMonth = 31;
            break;
        case 4:
            MonthOfName = "April";
            number_Of_DaysInMonth = 30;
            break;
        case 5:
            MonthOfName = "May";
            number_Of_DaysInMonth = 31;
            break;
        case 6:
            MonthOfName = "June";
            number_Of_DaysInMonth = 30;
            break;
        case 7:
            MonthOfName = "July";
            number_Of_DaysInMonth = 31;
            break;
        case 8:
            MonthOfName = "August";
            number_Of_DaysInMonth = 31;
            break;
        case 9:
            MonthOfName = "September";
            number_Of_DaysInMonth = 30;
            break;
        case 10:
            MonthOfName = "October";
            number_Of_DaysInMonth = 31;
            break;
        case 11:
            MonthOfName = "November";
            number_Of_DaysInMonth = 30;
            break;
        case 12:
            MonthOfName = "December";
            number_Of_DaysInMonth = 31;
    }
}

-1

这对我来说很好。

这是一个示例输出

import java.util.*;

public class DaysInMonth { 

    public static void main(String args []) { 

        Scanner input = new Scanner(System.in); 
        System.out.print("Enter a year:"); 

        int year = input.nextInt(); //Moved here to get input after the question is asked 

        System.out.print("Enter a month:"); 
        int month = input.nextInt(); //Moved here to get input after the question is asked 

        int days = 0; //changed so that it just initializes the variable to zero
        boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); 

        switch (month) { 
            case 1: 
                days = 31; 
                break; 
            case 2: 
                if (isLeapYear) 
                    days = 29; 
                else 
                    days = 28; 
                break; 
            case 3: 
                days = 31; 
                break; 
            case 4: 
                days = 30; 
                break; 
            case 5: 
                days = 31; 
                break; 
            case 6: 
                days = 30; 
                break; 
            case 7: 
                days = 31; 
                break; 
            case 8: 
                days = 31; 
                break; 
            case 9: 
                days = 30; 
                break; 
            case 10: 
                days = 31; 
                break; 
            case 11: 
                days = 30; 
                break; 
            case 12: 
                days = 31; 
                break; 
            default: 
                String response = "Have a Look at what you've done and try again";
                System.out.println(response); 
                System.exit(0); 
        } 

        String response = "There are " + days + " Days in Month " + month + " of Year " + year + ".\n"; 
        System.out.println(response); // new line to show the result to the screen. 
    } 
} //abhinavsthakur00@gmail.com

-1
String date = "11-02-2000";
String[] input = date.split("-");
int day = Integer.valueOf(input[0]);
int month = Integer.valueOf(input[1]);
int year = Integer.valueOf(input[2]);
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR,year);
cal.set(Calendar.MONTH,month-1);
cal.set(Calendar.DATE, day);
//since month number starts from 0 (i.e jan 0, feb 1), 
//we are subtracting original month by 1
int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println(days);

无需回答已经接受的问题,直到该答案无效为止。
Deepak
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.