日期与当地时间的差异



下载joda库,提取joda time计算时差,这是我的类,计算日期差异:(我使用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)新的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中,大写Yy的含义不同。在6中没有指定Y,因此它抛出以下异常:

java.lang.IllegalArgumentException: Illegal pattern character 'Y'

你的代码有两个问题,我可以看到(除了随机未使用的静态)。

  1. Y不是年份的格式代码,Y是。
  2. d2为空,则将两个字符串解析为d1。

下面的代码在今天运行时给了我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);

最新更新