任何人都可以告诉如何减去字符串""来自"今天"得到天差。
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);
}
}
答案 0 :(得分:4)
使用java8会更容易,你不需要减去代表日期的长值,然后再改回天,小时和分钟。
Date today= LocalDate.now();
Date futureDate = LocalDate.now().plusDays(1);
long days = Period.between(today, futureDate).getDays();
Period
& #java8
LocalDate
类
LocalDate
docs
LocalDate是一个表示日期的不可变日期时间对象, 通常被视为年月日。其他日期字段,例如 也可以访问日期,星期和星期。对于 例如,值“2007年10月2日”可以存储在LocalDate中。
如果您不使用java8,请使用joda-time library的org.joda.time.Days
实用程序来计算
Days day = Days.daysBetween(startDate, endDate);
int days = d.getDays();
答案 1 :(得分:3)
使用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
答案 2 :(得分: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.");
}
}
答案 3 :(得分:-1)
这可能对你有所帮助..
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");