[英]Date difference with joda time
我下载了joda库并提取了joda时间以计算时差,这是我的班级,它计算日期差:(我使用的是Java 1.7
)
public class TimeDiffereneceTest {
static String secondDate,firstDate, dateDifference;
public static void main(String[] args) {
firstDate = "2014/07/20";
secondDate = getTodayDate(); // Generate 2014/07/23
DateDifference(firstDate, secondDate);
}
public static String getTodayDate() {
Calendar todayDate = Calendar.getInstance();
SimpleDateFormat simpleFormat = new SimpleDateFormat("YYYY/MM/dd");
String strDate = simpleFormat.format(todayDate.getTime());
return strDate;
}
public static void DateDifference(String firstDate,String nowDate) {
Date d1=null;
Date d2=null;
SimpleDateFormat format = new SimpleDateFormat("YYYY/MM/dd");
try{
d1 = format.parse(firstDate);
d1 = format.parse(nowDate);
DateTime dt1 = new DateTime(d1);
DateTime dt2 = new DateTime(d2);
System.out.println("Day difference is: "+Days.daysBetween(dt1, dt2).getDays()); // 206!
}
catch(Exception e){
e.printStackTrace();
}
}
}
结果应该为3
因为今天的日期是2014/07/23
而第一个日期是"2014/07/20"
,但是结果有误( 206
)。
我看到一些代码问题:1)new SimpleDateFormat应该抛出非法参数,因为“ YYYY”应该是“ yyyy”(至少对我来说是可行的2)在DateDifference中(由于其方法而不是类,因此应命名为dateDifference)召集)
d1 = format.parse(firstDate);
d1 = format.parse(nowDate);
代替
d1 = simpleFormat.parse(firstDate);
d2 = simpleFormat.parse(nowDate);
尝试使用此代码,它对我有用。
public class TimeDiffereneceTest {
static String secondDate,firstDate, dateDifference;
static SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy/MM/dd");
public static void main(String[] args) {
firstDate = "2014/07/20";
secondDate = getTodayDate(); // Generate 2014/07/23
DateDifference(firstDate, secondDate);
}
public static String getTodayDate() {
Calendar todayDate = Calendar.getInstance();
String strDate = simpleFormat.format(todayDate.getTime());
return strDate;
}
public static void DateDifference(String firstDate,String nowDate) {
Date d1=null;
Date d2=null;
try{
d1 = simpleFormat.parse(firstDate);
d2 = simpleFormat.parse(nowDate);
DateTime dt1 = new DateTime(d1);
DateTime dt2 = new DateTime(d2);
System.out.println("Day difference is: "+Days.daysBetween(dt1, dt2).getDays()); // 206!
}
catch(Exception e){
e.printStackTrace();
}
}
}
您正在使用哪个Java版本?
在7中,大写的Y
与y
含义不同。 在6中未指定Y
因此会引发以下异常:
java.lang.IllegalArgumentException: Illegal pattern character 'Y'
您的代码有两个问题,我可以看到(除了随机未使用的静态数据)。
以下代码在今天运行时给了我4,即“ 2014/07/24”。
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
String firstDate = "2014/07/20";
String secondDate = format.format(new Date());
int days = Days.daysBetween(new DateTime(format.parse(firstDate)), new DateTime(format.parse(secondDate))).getDays();
System.out.println(days);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.