import org.apache.commons.lang.time.DurationFormatUtils; import java.util.Date; public class DateUtil { /** * 计算两个日期间隔多少年、多少月、多少天的实现 * * @param date * @return */ public static String getYearToDate(Date date){ Date now = new Date(); String formatPeriod = DurationFormatUtils.formatPeriod(date.getTime(), now.getTime(), "y-M-d"); String[] split = formatPeriod.split("-"); int year = Integer.parseInt(split[0]); int month = Integer.parseInt(split[1]); int day = Integer.parseInt(split[2]); StringBuilder sb = new StringBuilder(); if (year>0) { sb.append(year).append("年"); } if (month>0) { sb.append(month).append("月"); } if (day>0 && month==0) { sb.append(day).append("天"); } System.out.println(sb); return sb.toString(); } }
测试
public static void main(String[] args) throws Exception { System.out.println("当前系统时间: "+LocalDate.now()); String str = "1991-09-26 02:33:39"; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date date = format.parse(str); // 30年3月 getYearToDate(date); }