2012-01-13 92 views
0

我想計算兩個日期之間的天數差異。我的代碼在日期的年份沒有變化時工作正常,但是當我計算兩個日期之間的差異時(如2012年1月13日至2011年12月13日),它會給出負值。當我計算當前日期和未來日期之間的差異時,它也會給出錯誤的差異值。請幫幫我。先謝謝你。這裏是我的代碼:無法獲得java中兩個日期之間的天數差異

//getting values from text box 
String fromtext = from.getText().toString(); 
String totext = to.getText().toString(); 
//sdf if a simple date formatter 
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); 
Date fromdate = (Date) sdf.parse(fromtext); 
Date todate = (Date) sdf.parse(totext); 

Calendar fromcal = Calendar.getInstance(); 
Calendar tocal = Calendar.getInstance(); 


    fromcal.setTime(fromdate); 
    tocal.setTime(todate);// setting to date 


    int reportDays=(int)(todate.getTime()-fromdate.getTime())/(3600*24*1000); 

請告訴我什麼是計算天差的最好方法。

+0

看看[這個例子](http://www.roseindia.net/java/beginners/DateDifferent.shtml) – CloudyMarble 2012-01-13 06:55:12

回答

1

除了格式問題已經mentionned,你是可能會有溢出。 試試這個:

int reportDays=(int)((todate.getTime()-fromdate.getTime())/(3600*24*1000)); 
+0

添加正確的數據究竟這是我在做什麼wrong.It這麼多的工作正常now.Thank你...... :) – picaso 2012-01-13 07:37:05

6

日期輸入:13/01/201213/12/2011

格式似乎dd/MM/yyyy並且使用的是錯誤的(即MM/dd/yyyy

+0

對不起,它輸入的錯誤。但每當我給正確的格式,它返回負值... .... – picaso 2012-01-13 07:00:49

+0

請與代碼 – 2012-01-13 07:10:09

0

使用喬達時間將是最簡單的方法。

0

檢查驗證碼:

import java.util.Calendar; 

public class DateDifferent{ 
    public static void main(String[] args){ 
    Calendar calendar1 = Calendar.getInstance(); 
    Calendar calendar2 = Calendar.getInstance(); 
    calendar1.set(2007, 01, 10); 
    calendar2.set(2007, 07, 01); 
    long milliseconds1 = calendar1.getTimeInMillis(); 
    long milliseconds2 = calendar2.getTimeInMillis(); 
    long diff = milliseconds2 - milliseconds1; 
    long diffSeconds = diff/1000; 
    long diffMinutes = diff/(60 * 1000); 
    long diffHours = diff/(60 * 60 * 1000); 
    long diffDays = diff/(24 * 60 * 60 * 1000); 
    System.out.println("\nThe Date Different Example"); 
    System.out.println("Time in milliseconds: " + diff + " milliseconds."); 
    System.out.println("Time in seconds: " + diffSeconds + " seconds."); 
    System.out.println("Time in minutes: " + diffMinutes + " minutes."); 
    System.out.println("Time in hours: " + diffHours + " hours."); 
    System.out.println("Time in days: " + diffDays + " days."); 
    } 
} 
0

這裏有一個簡單的小類我寫了這個目的:

import java.text.DateFormat; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

public class DifferenceInDays 
{ 
    public int dateOffset(String incomingDate) throws ParseException 
    { 
     // parse dates 
     DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
     Date date = (Date) formatter.parse(incomingDate); 

     // convert to milliseconds 
     long millisecs = date.getTime(); 

     // convert to days 
     int offsetInDays = (int) Math.abs(millisecs/(1000 * 60 * 60 * 24)); 
     return offsetInDays; 
    } 
} 

它需要使用絕對值方法負偏移的照顧。

0

如果您使用具有夏令時的區域設置進行此操作,並且夏令時開始前和結束日期都是夏令時之前和之後,則結果可能會相差1天。這是因爲DateCalendar使用時區。

如果你只打算來對付年1900和2100之間的日期,有一個簡單的計算,這將給你自1900年以來的天數:

public static int daysSince1900(Date date) { 
    Calendar c = new GregorianCalendar(); 
    c.setTime(date); 

    int year = c.get(Calendar.YEAR); 
    if (year < 1900 || year > 2099) { 
     throw new IllegalArgumentException("daysSince1900 - Date must be between 1900 and 2099"); 
    } 
    year -= 1900; 
    int month = c.get(Calendar.MONTH) + 1; 
    int days = c.get(Calendar.DAY_OF_MONTH); 

    if (month < 3) { 
     month += 12; 
     year--; 
    } 
    int yearDays = (int) (year * 365.25); 
    int monthDays = (int) ((month + 1) * 30.61); 

    return (yearDays + monthDays + days - 63); 
} 

因此,爲了獲得差異在兩個日期之間的天數中,計算自1900年以來的天數並計算差異。我們daysBetween方法是這樣的:

public static Integer getDaysBetween(Date date1, Date date2) { 
    if (date1 == null || date2 == null) { 
     return null; 
    } 

    int days1 = daysSince1900(date1); 
    int days2 = daysSince1900(date2); 

    if (days1 < days2) { 
     return days2 - days1; 
    } else { 
     return days1 - days2; 
    } 
} 

不要問我在哪裏,這個計算從因爲我們自從90年代初用它來了。

+0

謝謝你親愛的......謝謝很多...:) – picaso 2012-03-07 08:04:59

0

TL;博士

ChronoUnit.DAYS.between(
    LocalDate.parse("13/01/2012" , DateTimeFormatter.ofPattern("dd/MM/uuuu")) , 
    LocalDate.parse("13/12/2011" , DateTimeFormatter.ofPattern("dd/MM/uuuu")) 
) 

使用java.time

與取代的麻煩舊的遺留日期時間類,如Date & Calendar現代java.time類容易得多。

(13/01/2012 to 13/12/2011), 

LocalDate類表示沒有時間一天和不同時區的日期,唯一的價值。使用ChronoUnit計算經過的天數。

long days = ChronoUnit.DAYS.between(start , stop); 

當然,返回時間的天數爲負數。注意您的止損日期早於您的開始日期。

時區對確定日期至關重要。對於任何特定的時刻,日期因地區而異。例如,Paris France午夜後幾分鐘是新的一天,而在Montréal Québec仍然是「昨天」。

continent/region的格式指定一個proper time zone name,如America/MontrealAfrica/Casablanca,或Pacific/Auckland。切勿使用3-4字母縮寫,如ESTIST,因爲它們是而不是真正的時區,不是標準化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of("America/Montreal"); 
LocalDate today = LocalDate.now(z); 

您可以再次使用ChronoUnit來計算未來的日子。

long days = ChronoUnit.DAYS.between(today , today.plusMonths(7)); 

關於java.time

java.time框架是建立在Java 8和更高版本。這些類取代了日期時間類legacy,如java.util.Date,Calendar,& SimpleDateFormat

Joda-Time項目現在位於maintenance mode,建議遷移到java.time類。請參閱Oracle Tutorial。並搜索堆棧溢出了很多例子和解釋。規格是JSR 310

從何處獲取java.time類?

ThreeTen-Extra項目與其他類擴展java.time。這個項目是未來可能增加java.time的一個試驗場。您可以在這裏找到一些有用的類,如Interval,YearWeek,YearQuartermore