目录
获取当月第一天和最后一天
LocalDate date = LocalDate.now();//当前日期
int year = date.getYear();//年
int month = date.getMonthValue();//月
String startDate = LocalDate.of(year, month, 1).toString();//第一天
String endDate = date.withDayOfMonth(date.getMonth().maxLength()).toString();//最后一天
上述方式可能抛出异常 DateTimeException
2025年2月只有28号,maxLength() 该方法返回月份的理论最大天数(2月固定为29天),没有考虑闰年的情况
可用下述方式:
LocalDate currentDate = LocalDate.now();
// 获取首日,参数为“0”代表当月,“1”代表上月,“-1”代表下月
LocalDate startDate = currentDate.minusMonths(-1).withDayOfMonth(1);
map.put("startDate", startDate.format(DateTimeFormatter.ISO_DATE));
// 获取本月末日
LocalDate endDate = YearMonth.from(currentDate).atEndOfMonth();
map.put("endDate", endDate.format(DateTimeFormatter.ISO_DATE));
获取当日前一天,前一天的月一号
LocalDate date = LocalDate.now();
LocalDate endDate = date.minusDays(1);//前一天
LocalDate startDate = endDate.withDayOfMonth(1);//前一天的月一号
计算日期差
import java.time.temporal.ChronoUnit;
long between = ChronoUnit.DAYS.between(startDate, endDate);
说明:
- startDate < endDate 返回正数,例如:1956-09-12 < 1956-09-13 返回 1
- startDate > endDate 返回负数,例如:1956-09-13 < 1956-09-12 返回 -1
- startDate = endDate 返回0,例如:1956-09-12 = 1956-09-12 返回 0
时间戳转Date
import java.util.Date;
Date date = new Date(Long.parseLong(dateTime));//时间戳为字符需转Long
Date转指定格式String
import java.text.SimpleDateFormat;
String formatDate = new SimpleDateFormat("yyyy/MM/dd").format(date);//传入Date类型
String日期转Date
import java.time.LocalDate;
LocalDate stringDate = LocalDate.parse("1956-09-12");
Date date = Date.from(stringDate.atStartOfDay(ZoneId.systemDefault()).toInstant());