Number of days in particular month of particular y

2019-01-01 12:54发布

How to know how many days has particular month of particular year?

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

16条回答
爱死公子算了
2楼-- · 2019-01-01 13:20
    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);
查看更多
妖精总统
3楼-- · 2019-01-01 13:22

You can use Calendar.getActualMaximum method:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
int numDays = calendar.getActualMaximum(Calendar.DATE);
查看更多
若你有天会懂
4楼-- · 2019-01-01 13:25

Code for java.util.Calendar

If you have to use java.util.Calendar, I suspect you want:

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

Code for Joda Time

Personally, however, I'd suggest using Joda Time instead of java.util.{Calendar, Date} to start with, in which case you could use:

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

Note that rather than parsing the string values individually, it would be better to get whichever date/time API you're using to parse it. In java.util.* you might use SimpleDateFormat; in Joda Time you'd use a DateTimeFormatter.

查看更多
深知你不懂我心
5楼-- · 2019-01-01 13:26

java.time.LocalDate

From Java 1.8, you can use the method lengthOfMonth on java.time.LocalDate:

LocalDate date = LocalDate.of(2010, 1, 19);
int days = date.lengthOfMonth();
查看更多
登录 后发表回答