[英]unable to get difference of days between two dates in java
我想計算兩個日期之間的天數差異。 當日期的年份不變時,我的代碼可以正常工作,但是當我像這樣計算兩個日期之間的差時:(13/01/2012到13/12/2011),它給出一個負值。 當我計算今天的日期和將來的日期之間的差異時,它也會給出錯誤的差異值。 請幫我。 先感謝您。 這是我的代碼:
//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);
請告訴我計算天數差異的最佳方法是什么。
日期輸入: 13/01/2012
, 13/12/2011
格式似乎是dd/MM/yyyy
而您使用的是錯誤的格式(例如MM/dd/yyyy
)
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
容易得多。
(13/01/2012 to 13/12/2011),
LocalDate
類表示沒有日期和時區的僅日期值。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate start = LocalDate.parse( "13/01/2012" , f );
LocalDate stop = LocalDate.parse( "13/12/2011" , f );
使用ChronoUnit
計算經過的天數。
long days = ChronoUnit.DAYS.between( start , stop );
當然,時光倒流的天數是負數。 請注意您的停止日期早於開始日期。
時區對於確定日期至關重要。 在任何給定時刻,日期都會在全球范圍內變化。 例如, 法國巴黎午夜過后幾分鍾是新的一天,而在魁北克蒙特利爾仍然是“昨天”。
以continent/region
的格式指定正確的時區名稱 ,例如America/Montreal
, Africa/Casablanca
或Pacific/Auckland
。 切勿使用EST
或IST
等3-4個字母的縮寫,因為它們不是真實的時區,不是標准化的,甚至不是唯一的(!)。
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
您可以再次使用ChronoUnit
來計算未來的天數。
long days = ChronoUnit.DAYS.between( today , today.plusMonths( 7 ) );
java.time框架內置於Java 8及更高版本中。 這些類取代了麻煩的舊的舊式日期時間類,例如java.util.Date
, Calendar
和SimpleDateFormat
。
現在處於維護模式的Joda-Time項目建議遷移到java.time類。
要了解更多信息,請參見Oracle教程 。 並在Stack Overflow中搜索許多示例和說明。 規格為JSR 310 。
在哪里獲取java.time類?
ThreeTen-Extra項目使用其他類擴展了java.time。 該項目為將來可能在java.time中添加內容提供了一個試驗場。 您可以在這里找到一些有用的類,比如Interval
, YearWeek
, YearQuarter
,和更多 。
除了已經提到的格式問題之外,您還可能會溢出。 嘗試這個:
int reportDays=(int)((todate.getTime()-fromdate.getTime())/(3600*24*1000));
我會這樣!
package javaapplication2;
//@author Ibrahim Yesilay
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String[] args) throws ParseException {
Scanner scan = new Scanner(System.in);
System.out.println("First dates Day :");
int d = scan.nextInt();
System.out.println("First dates Mounth :");
int m = scan.nextInt();
System.out.println("First dates Year :");
int y = scan.nextInt();
String date;
date = Integer.toString(d) + "/" + Integer.toString(m) + "/" + Integer.toString(y);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date firstdate = null;
firstdate = dateFormat.parse(date);
System.out.println(dateFormat.format(firstdate));
System.out.println("Second dates Day :");
d = scan.nextInt();
System.out.println("Second dates Month :");
m = scan.nextInt();
System.out.println("Second dates Year :");
y = scan.nextInt();
date = Integer.toString(d) + "/" + Integer.toString(m) + "/" + Integer.toString(y);
Date seconddate = null;
seconddate = dateFormat.parse(date);
System.out.println(dateFormat.format(seconddate));
if (seconddate.getTime() > firstdate.getTime()) {
long sonuc = (long)(seconddate.getTime()- firstdate.getTime())/(3600*24*1000);
System.out.println("" + sonuc);
} else if (firstdate.getTime() > seconddate.getTime()) {
long sonuc = (long)(firstdate.getTime()- seconddate.getTime())/(3600*24*1000);
System.out.println("" + sonuc);
} else {
System.out.println("The dates are equal!");
}
}
}
使用joda時間將是最簡單的方法。
檢查此代碼:
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.");
}
}
這是我為此目的編寫的一個簡單的小類:
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;
}
}
它使用絕對值方法處理負偏移。
如果您在具有夏令時的語言環境中嘗試此操作,並且起始和結束日期在夏令時之前和之后,則結果可能會相差1天。 這是因為Date
和Calendar
使用時區。
如果您僅要處理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年代初就開始使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.