DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM");
LocalDate afterDate = LocalDate.of(2021, 1, 9);
YearMonth afterMonth = YearMonth.parse(sdf.format(afterDate), sdf);
LocalDate beforeDate = LocalDate.of(2019, 2, 10);
YearMonth beforeMonth = YearMonth.parse(sdf.format(beforeDate), sdf);
int monDif = afterMonth.getMonthValue() - beforeMonth.getMonthValue();
System.out.println("monDif:" + monDif);
int month = (afterMonth.getYear() - beforeMonth.getYear())*12;
System.out.println("month:"+ month);
System.out.println("month+monDif:" + (month+monDif));
方法 2 (推荐, 计算时还会把天也计算上)
LocalDate afterDate = LocalDate.of(2021, 1, 9);
LocalDate beforeDate = LocalDate.of(2019, 2, 10);
long betweenMONTHS = ChronoUnit.MONTHS.between(beforeDate, afterDate);
long between1YEARS = ChronoUnit.YEARS.between(beforeDate, afterDate);
long between1DAYS = ChronoUnit.DAYS.between(beforeDate, afterDate);
System.out.println(betweenMONTHS);
System.out.println(between1YEARS);
System.out.println(between1DAYS);
Java8java8中计算2个日期时间之间相差多少月方法一 DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM"); //未来时间 LocalDate afterDate = LocalDate.of(2021, 1, 9); YearMonth afterMonth =...
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
String
要求 Java 8 中两个 LocalDateTime 类型时间相差的月数,可以使用以下代码:
long monthsBetween = ChronoUnit.MONTHS.between(dateTime1, dateTime2);
其中,dateTime1 和 dateTime2 是你想要比较的两个 LocalDateTime 类型的时间。
这段代码会返回一个 long 类型的数字,表示两个...
* 获取两个日期相差几个月
* @author 石冬冬-Heil Hilter(dd.shi02@zuche.com)
* @date 2016-11-30 下午7:57:32
* @param start
* @param end
* @return
public static int getMonth(
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
public class Test1 {
public static void main(String[] args) {
//LocalDat...
@Test
public void contextLoads() {
LocalDate localDateTime1 = getLocalDateTime(1590541609000L). toLocalDate();
LocalDate localDateTime2 = getLocalDateTime(1598404009000L). tolocalDate();
System.out.println(Period.between(local.
迂回战术:获取两个日期之间的天数。除以7等于相隔多少周。
参考链接:https://blog.csdn.net/kevin_mails/article/details/78440696
package com.test;
import java.time.LocalDate;
import java.time.Month;
import...
public class DateUtils {
public static long daysBetween(LocalDate startDate, LocalDate endDate) {
return ChronoUnit.DAYS.between(startDate, endDate);
// 调用方法
LocalDate startDate = LocalDate.of(2021, 1, 1);
LocalDate endDate = LocalDate.of(2021, 1, 10);
long days = DateUtils.daysBetween(startDate, endDate);
System.out.println("相差天数:" + days);
以上代码中,我们使用了Java 8中的日期类LocalDate和ChronoUnit来计算两个日期之间相差的天数。其中,LocalDate表示一个日期,ChronoUnit.DAYS表示计算两个日期之间相差的天数。