减去日期并获得天数差异。如何减去它们?

任何人都可以告诉如何从“今天”减去字符串“后”以获得天差。

import java.text.*; import java.util.*; public class Main { public static void main(String args[]){ SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd"); Calendar cal=Calendar.getInstance(); String today=sdf.format(cal.getTime()); System.out.println(today); cal.add(Calendar.DATE, 20); String After=sdf.format(cal.getTime()); System.out.println(After); } } 

使用java8会更容易,您不需要减去表示日期的长值,并将其更改回天,小时和分钟。

 Date today= LocalDate.now(); Date futureDate = LocalDate.now().plusDays(1); long days = Period.between(today, futureDate).getDays(); 

PeriodLocalDate类在#java8中可用

LocalDate文档

LocalDate是一个不可变的日期时间对象,表示日期,通常被视为年 – 月 – 日。 还可以访问其他日期字段,例如日期,星期几和星期。 例如,值“2007年10月2日”可以存储在LocalDate中。


如果您不使用java8,请使用joda-time库的org.joda.time.Days实用程序来计算

 Days day = Days.daysBetween(startDate, endDate); int days = d.getDays(); 

使用JodaTime ,以防您没有Java 8

 String timeValue = "2014/11/11"; DateTimeFormatter parseFormat = new DateTimeFormatterBuilder().appendPattern("yyyy/MM/dd").toFormatter(); LocalDate startDate = LocalDate.parse(timeValue, parseFormat); LocalDate endDate = startDate.plusDays(20); System.out.println(startDate + "; " + endDate); Period p = new Period(startDate, endDate); System.out.println("Days = " + p.getDays()); System.out.println("Weeks = " + p.getWeeks()); System.out.println("Months = " + p.getMonths()); 

哪个输出……

 2014-11-11; 2014-12-01 Days = 6 Weeks = 2 Months = 0 

试试这个…

愿它帮到你。

 import java.util.Date; import java.util.GregorianCalendar; // compute the difference between two dates. public class DateDiff { public static void main(String[] av) { /** The date at the end of the last century */ Date d1 = new GregorianCalendar(2010, 10, 10, 11, 59).getTime(); /** Today's date */ Date today = new Date(); // Get msec from each, and subtract. long diff = today.getTime() - d1.getTime(); System.out.println("The 21st century (up to " + today + ") is " + (diff / (1000 * 60 * 60 * 24)) + " days old."); } } 

这可能对你有所帮助..

 SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd"); Calendar cal=Calendar.getInstance(); String today=sdf.format(cal.getTime()); System.out.println(today); cal.add(Calendar.DATE, 20); String After=sdf.format(cal.getTime()); System.out.println(After); Date d1 = null; Date d2 = null; SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); try { d1 = format.parse(today); d2 = format.parse(After); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } long diff = d2.getTime() - d1.getTime(); long diffDays = diff / (24 * 60 * 60 * 1000); System.out.println("Difference is "+diffDays+" Days");