[英]unable to get difference of days between two dates in java
I want to calculate the difference of days between two dates. 我想计算两个日期之间的天数差异。 My code works fine when the year of the date does not change, but when I calculate the difference between two dates like so: (13/01/2012 to 13/12/2011), it gives a negative value.
当日期的年份不变时,我的代码可以正常工作,但是当我像这样计算两个日期之间的差时:(13/01/2012到13/12/2011),它给出一个负值。 It also gives wrong values of difference when I calculate the difference between today's date and a future date.
当我计算今天的日期和将来的日期之间的差异时,它也会给出错误的差异值。 Please help me.
请帮我。 Thank you in advance.
先感谢您。 Here is my code:
这是我的代码:
//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);
please tell me what is the best way to calculate the difference in days. 请告诉我计算天数差异的最佳方法是什么。
Dates input : 13/01/2012
, 13/12/2011
日期输入:
13/01/2012
, 13/12/2011
format seems dd/MM/yyyy
and you are using wrong one (ie MM/dd/yyyy
) 格式似乎是
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" ) )
)
Much easier with the modern java.time classes that supplant the troublesome old legacy date-time classes such as Date
& Calendar
. 用现代的java.time类替代麻烦的旧的传统日期时间类(例如
Date
& Calendar
容易得多。
(13/01/2012 to 13/12/2011),
The LocalDate
class represents a date-only value without time-of-day and without time zone. LocalDate
类表示没有日期和时区的仅日期值。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate start = LocalDate.parse( "13/01/2012" , f );
LocalDate stop = LocalDate.parse( "13/12/2011" , f );
Use ChronoUnit
to calculate elapsed days. 使用
ChronoUnit
计算经过的天数。
long days = ChronoUnit.DAYS.between( start , stop );
Of course the number of days is negative when going back in time. 当然,时光倒流的天数是负数。 Notice how your stop date is earlier than your start date.
请注意您的停止日期早于开始日期。
A time zone is crucial in determining a date. 时区对于确定日期至关重要。 For any given moment, the date varies around the globe by zone.
在任何给定时刻,日期都会在全球范围内变化。 For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec .
例如, 法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天”。
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. 以
continent/region
的格式指定正确的时区名称 ,例如America/Montreal
, Africa/Casablanca
或Pacific/Auckland
。 Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!). 切勿使用
EST
或IST
等3-4个字母的缩写,因为它们不是真实的时区,不是标准化的,甚至不是唯一的(!)。
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
You can use ChronoUnit
again to count days into the future. 您可以再次使用
ChronoUnit
来计算未来的天数。
long days = ChronoUnit.DAYS.between( today , today.plusMonths( 7 ) );
The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
, Calendar
, & SimpleDateFormat
. 这些类取代了麻烦的旧的旧式日期时间类,例如
java.util.Date
, Calendar
和SimpleDateFormat
。
The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial . 要了解更多信息,请参见Oracle教程 。 And search Stack Overflow for many examples and explanations.
并在Stack Overflow中搜索许多示例和说明。 Specification is JSR 310 .
规格为JSR 310 。
Where to obtain the java.time classes? 在哪里获取java.time类?
The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time.
该项目为将来可能在java.time中添加内容提供了一个试验场。 You may find some useful classes here such as
Interval
, YearWeek
, YearQuarter
, and more . 您可以在这里找到一些有用的类,比如
Interval
, YearWeek
, YearQuarter
,和更多 。
I think you should try better googling.... 我认为您应该尝试更好的谷歌搜索。
In addition to the format issue already mentionned, you are likely to have an overflow. 除了已经提到的格式问题之外,您还可能会溢出。 Try this:
尝试这个:
int reportDays=(int)((todate.getTime()-fromdate.getTime())/(3600*24*1000));
I would do it like this! 我会这样!
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时间将是最简单的方法。
check this code: 检查此代码:
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.");
}
}
Here's a simple little class I wrote for this purpose: 这是我为此目的编写的一个简单的小类:
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;
}
}
It takes care of negative offsets using the absolute value method. 它使用绝对值方法处理负偏移。
If you try this with a locale that has daylight saving, and the from and to dates are before and after a daylight saving change the result may be different by 1 day. 如果您在具有夏令时的语言环境中尝试此操作,并且起始和结束日期在夏令时之前和之后,则结果可能会相差1天。 This is because
Date
and Calendar
use timezones. 这是因为
Date
和Calendar
使用时区。
If you are only going to be dealing with dates between the years 1900 and 2100, there is a simple calculation which will give you the number of days since 1900: 如果您仅要处理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);
}
Thus, to get the difference in days between two dates, you calculate their days since 1900 and calc the difference. 因此,要获取两个日期之间的天数差异,您可以计算它们自1900年以来的天数并计算差异。 Our daysBetween method looks like this:
我们的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;
}
}
And don't ask me where this calculation came from because we've used it since the early '90s. 而且不要问我这个计算的来源,因为我们从90年代初就开始使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.