java怎样获取年份和月份_java获取给定月份和给定年份的第一个日期和最后日期...

参见英文答案 > How to get the first date and last date of the previous month? (Java)                                    7个

我想获得给定月份和年份的第一个日期和最后日期.我使用以下代码以yyyyMMdd格式获取最后一个日期.但是无法获得这种格式.然后我想以相同的格式开始日期.我还在努力.任何人都可以帮我修复下面的代码.

public static java.util.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);

java.util.Date monthEndDate = new java.util.Date(gc.getTime().getTime());

return monthEndDate;

}

public static void main(String[] args) {

int month = 3;

int year = 2076;

final java.util.Date calculatedDate = calculateMonthEndDate(month, year);

SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

format.format(calculatedDate);

System.out.println("Calculated month end date : " + calculatedDate);

}

解决方法:

获取开始日期

GregorianCalendar gc = new GregorianCalendar(year, month-1, 1);

java.util.Date monthEndDate = new java.util.Date(gc.getTime().getTime());

System.out.println(monthEndDate);

(注意:在开始日期当天= 1)

为格式化

SimpleDateFormat format = new SimpleDateFormat(/add your format here);

System.out.println("Calculated month end date : " + format.format(calculatedDate));

标签:java,date,calendar

来源: https://codeday.me/bug/20191004/1854170.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值