Java通过cal.get(Calendar.MONTH)比真实月份少了一个月

博客指出在Java里,通过查阅资料发现月份是从0开始计算的,范围为0 - 11。

通过查阅资料之发现,这里月份是从0开始计算的,也就是说,月份是从0—11。

package com.hundsun.amop.tgfacade.server.util; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateComputerUtils { /** * 根据给定的 endDate 计算“上年年末”日期(格式:yyyyMMdd) */ public static int getLastYearEnd(Date endDate) { Calendar cal = Calendar.getInstance(); cal.setTime(endDate); int currentYear = cal.get(Calendar.YEAR); // 获取当前年份 int lastYear = currentYear - 1; // 构造去年12月31日 cal.set(lastYear, Calendar.DECEMBER, 31, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); return lastYear * 10000 + 12 * 100 + 31; // 返回 int:如 20231231 } /** * 根据输入日期获取当年年初(1月1日),返回 int 格式的 yyyyMMdd */ public static int getYearStart(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); int year = cal.get(Calendar.YEAR); // 获取年份 return year * 10000 + 101; // 构造成 yyyyMMdd 格式 } /** * 根据给定的日期计算“上一自然日”,返回 int 类型的 yyyyMMdd */ public static int getPreviousDay(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DAY_OF_MONTH, -1); // 减一天 int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1; // 月份从0开始 int day = cal.get(Calendar.DAY_OF_MONTH); return year * 10000 + month * 100 + day; } //日期类型转int八位 public static Integer dateTo8DigitNumber(Date date) { if (date == null) return null; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String dateStr = sdf.format(date); return Integer.valueOf(dateStr); } // 获取当前最新时间,返回 yyyyMMdd 格式的 8 位整数 public static int getYYMMDDDate() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); // 改为四位年份 String dateStr = sdf.format(new Date()); return Integer.parseInt(dateStr); } public static int convertToEightDigit(String effectiveDate) { if (null == effectiveDate || !effectiveDate.matches("\\d{4}-\\d{2}-\\d{2}")) { throw new IllegalArgumentException("Invalid date format: " + effectiveDate); } String noHyphen = effectiveDate.replace("-", ""); return Integer.parseInt(noHyphen); } } 格式美化
最新发布
12-03
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值