我使用以下代码获取当前日期(格式为12/31/1999,即mm / dd / yyyy):
Textview txtViewData;
txtViewDate.setText("Today is " +
android.text.format.DateFormat.getDateFormat(this).format(new Date()));
我还有另一个日期格式为:2010-08-25(即yyyy / mm / dd),
所以我想找出日期的天数之间的差异,我如何找到天数的差异?
(换句话说,我想找到 CURRENT DATE - yyyy / mm / dd格式化日期之间的区别)
答案 0 :(得分:123)
不是真正可靠的方法,更好地使用JodaTime
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
这是一个近似值......
long days = diff / (24 * 60 * 60 * 1000);
要从字符串中解析日期,可以使用
String strThatDay = "1985/08/25";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
d = formatter.parse(strThatDay);//catch exception
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....
虽然,因为你确定日期格式......
您也可以在其子字符串上Integer.parseInt()
获取其数值。
答案 1 :(得分:79)
这不是我的工作,找到了答案here。不希望将来发生断链:)。
关键是考虑日光设置的这一行,参考完整代码。
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
或尝试将TimeZone
作为参数传递给daysBetween()
,并在setTimeZone()
和sDate
个对象中调用eDate
。
这就是:
public static Calendar getDatePart(Date date){
Calendar cal = Calendar.getInstance(); // get calendar instance
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0); // set hour to midnight
cal.set(Calendar.MINUTE, 0); // set minute in hour
cal.set(Calendar.SECOND, 0); // set second in minute
cal.set(Calendar.MILLISECOND, 0); // set millisecond in second
return cal; // return the date part
}
getDatePart()取自here
/**
* This method also assumes endDate >= startDate
**/
public static long daysBetween(Date startDate, Date endDate) {
Calendar sDate = getDatePart(startDate);
Calendar eDate = getDatePart(endDate);
long daysBetween = 0;
while (sDate.before(eDate)) {
sDate.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
细微差别: 找到两个日期之间的差异并不像减去两个日期并将结果除以(24 * 60 * 60 * 1000)那样简单。事实上,它的错误!
例如:两个日期03/24/2007和03/25/2007之间的差异应为1天;但是,使用上述方法,在英国,你将获得0天!
自己看看(下面的代码)。以毫秒为单位将导致错误四舍五入,一旦你有了像夏令时这样的小东西,它们就会变得非常明显。
完整代码:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class DateTest {
public class DateTest {
static SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
//diff between these 2 dates should be 1
Date d1 = new Date("01/01/2007 12:00:00");
Date d2 = new Date("01/02/2007 12:00:00");
//diff between these 2 dates should be 1
Date d3 = new Date("03/24/2007 12:00:00");
Date d4 = new Date("03/25/2007 12:00:00");
Calendar cal1 = Calendar.getInstance();cal1.setTime(d1);
Calendar cal2 = Calendar.getInstance();cal2.setTime(d2);
Calendar cal3 = Calendar.getInstance();cal3.setTime(d3);
Calendar cal4 = Calendar.getInstance();cal4.setTime(d4);
printOutput("Manual ", d1, d2, calculateDays(d1, d2));
printOutput("Calendar ", d1, d2, daysBetween(cal1, cal2));
System.out.println("---");
printOutput("Manual ", d3, d4, calculateDays(d3, d4));
printOutput("Calendar ", d3, d4, daysBetween(cal3, cal4));
}
private static void printOutput(String type, Date d1, Date d2, long result) {
System.out.println(type+ "- Days between: " + sdf.format(d1)
+ " and " + sdf.format(d2) + " is: " + result);
}
/** Manual Method - YIELDS INCORRECT RESULTS - DO NOT USE**/
/* This method is used to find the no of days between the given dates */
public static long calculateDays(Date dateEarly, Date dateLater) {
return (dateLater.getTime() - dateEarly.getTime()) / (24 * 60 * 60 * 1000);
}
/** Using Calendar - THE CORRECT WAY**/
public static long daysBetween(Date startDate, Date endDate) {
...
}
<强>输出:强>
手册 - 2007年1月1日至2007年1月2日之间的天数为:1
日历 - 日期:2007年1月1日至2007年1月2日期间:1
手册 - 2007年3月24日至2007年3月25日之间的天数为:0
日历 - 日期:2007年3月24日至2007年3月25日期间:1
答案 2 :(得分:36)
大多数答案都很好,适合您的
问题所以我想找出日期的天数之间的差异,我如何找到天数的差异?
我建议这种非常简单明了的方法可以保证在任何时区给你正确的差异:
int difference=
((int)((startDate.getTime()/(24*60*60*1000))
-(int)(endDate.getTime()/(24*60*60*1000))));
就是这样!
答案 3 :(得分:23)
Days.daysBetween(start.toDateMidnight() , end.toDateMidnight() ).getDays()
其中'start'和'end'是您的DateTime个对象。要将日期字符串解析为DateTime对象,请使用parseDateTime method
答案 4 :(得分:14)
此片段占夏令时,为O(1)。
private final static long MILLISECS_PER_DAY = 24 * 60 * 60 * 1000;
private static long getDateToLong(Date date) {
return Date.UTC(date.getYear(), date.getMonth(), date.getDate(), 0, 0, 0);
}
public static int getSignedDiffInDays(Date beginDate, Date endDate) {
long beginMS = getDateToLong(beginDate);
long endMS = getDateToLong(endDate);
long diff = (endMS - beginMS) / (MILLISECS_PER_DAY);
return (int)diff;
}
public static int getUnsignedDiffInDays(Date beginDate, Date endDate) {
return Math.abs(getSignedDiffInDays(beginDate, endDate));
}
答案 5 :(得分:6)
这对我来说是简单而且最好的计算方式,可能适合您。
try {
/// String CurrDate= "10/6/2013";
/// String PrvvDate= "10/7/2013";
Date date1 = null;
Date date2 = null;
SimpleDateFormat df = new SimpleDateFormat("M/dd/yyyy");
date1 = df.parse(CurrDate);
date2 = df.parse(PrvvDate);
long diff = Math.abs(date1.getTime() - date2.getTime());
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println(diffDays);
} catch (Exception e1) {
System.out.println("exception " + e1);
}
答案 6 :(得分:3)
Sam Quest的答案中的Correct Way
仅在第一个日期早于第二个日期时才有效。此外,如果两个日期都在一天之内,它将返回1。
这是最适合我的解决方案。就像大多数其他解决方案一样,由于日光节省偏差错误,一年中的两天仍会显示不正确的结果。
private final static long MILLISECS_PER_DAY = 24 * 60 * 60 * 1000;
long calculateDeltaInDays(Calendar a, Calendar b) {
// Optional: avoid cloning objects if it is the same day
if(a.get(Calendar.ERA) == b.get(Calendar.ERA)
&& a.get(Calendar.YEAR) == b.get(Calendar.YEAR)
&& a.get(Calendar.DAY_OF_YEAR) == b.get(Calendar.DAY_OF_YEAR)) {
return 0;
}
Calendar a2 = (Calendar) a.clone();
Calendar b2 = (Calendar) b.clone();
a2.set(Calendar.HOUR_OF_DAY, 0);
a2.set(Calendar.MINUTE, 0);
a2.set(Calendar.SECOND, 0);
a2.set(Calendar.MILLISECOND, 0);
b2.set(Calendar.HOUR_OF_DAY, 0);
b2.set(Calendar.MINUTE, 0);
b2.set(Calendar.SECOND, 0);
b2.set(Calendar.MILLISECOND, 0);
long diff = a2.getTimeInMillis() - b2.getTimeInMillis();
long days = diff / MILLISECS_PER_DAY;
return Math.abs(days);
}
答案 7 :(得分:3)
最好和最简单的方法
public int getDays(String begin) throws ParseException {
long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
long begin = dateFormat.parse(begin).getTime();
long end = new Date().getTime(); // 2nd date want to compare
long diff = (end - begin) / (MILLIS_PER_DAY);
return (int) diff;
}
答案 8 :(得分:3)
ChronoUnit.DAYS.between(
LocalDate.parse( "1999-12-28" ) ,
LocalDate.parse( "12/31/1999" , DateTimeFormatter.ofPattern( "MM/dd/yyyy" ) )
)
其他答案已过时。与最早版本的Java捆绑在一起的旧日期时间类已被证明设计糟糕,令人困惑且麻烦。避免它们。
Joda-Time项目非常成功,取代了那些旧班级。这些类为Java 8及更高版本中内置的java.time框架提供了灵感。
大部分java.time功能都被反向移植到Java 6&amp; ThreeTen-Backport中的7,并在ThreeTenABP中进一步适应Android。
LocalDate
LocalDate
类表示没有时间且没有时区的仅限日期的值。
如果输入字符串采用标准ISO 8601格式,LocalDate
类可以直接解析字符串。
LocalDate start = LocalDate.parse( "1999-12-28" );
如果不是ISO 8601格式,请使用DateTimeFormatter
定义格式设置模式。
String input = "12/31/1999";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM/dd/yyyy" );
LocalDate stop = LocalDate.parse( input , formatter );
ChronoUnit
现在获取该对LocalDate
个对象之间经过的天数。 ChronoUnit
枚举计算已用时间。
long totalDays = ChronoUnit.DAYS.between( start , stop ) ;
如果您不熟悉Java枚举,请知道它们比大多数其他编程语言中的常规枚举更强大,更有用。请参阅Enum
课程文档,Oracle Tutorial和Wikipedia了解详情。
java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.Date
,Calendar
和&amp; SimpleDateFormat
现在位于Joda-Time的maintenance mode项目建议迁移到java.time类。
要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310。
从哪里获取java.time类?
ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如Interval
,YearWeek
,YearQuarter
和more。
答案 9 :(得分:2)
有一个简单的解决方案,至少对我来说,是唯一可行的解决方案。
问题是我看到的所有答案都被抛到了 - 使用Joda,或Calendar,或者其他什么 - 只需要考虑毫秒数。他们最终计算两个日期之间的 24小时循环次数,而不是实际天数。所以从1月1日晚上11点到1月2日凌晨1点将返回0天。
要计算startDate
和endDate
之间的实际天数,只需执行以下操作:
// Find the sequential day from a date, essentially resetting time to start of the day
long startDay = startDate.getTime() / 1000 / 60 / 60 / 24;
long endDay = endDate.getTime() / 1000 / 60 / 60 / 24;
// Find the difference, duh
long daysBetween = endDay - startDay;
这将在1月2日到1月1日之间返回“1”。如果您需要计算结束日期,只需在daysBetween
中添加1(我需要在我的代码中执行此操作,因为我想计算范围内的总天数)。
这有点类似Daniel has suggested但我想的更小的代码。
答案 10 :(得分:2)
使用以下功能:
/**
* Returns the number of days between two dates. The time part of the
* days is ignored in this calculation, so 2007-01-01 13:00 and 2007-01-02 05:00
* have one day inbetween.
*/
public static long daysBetween(Date firstDate, Date secondDate) {
// We only use the date part of the given dates
long firstSeconds = truncateToDate(firstDate).getTime()/1000;
long secondSeconds = truncateToDate(secondDate).getTime()/1000;
// Just taking the difference of the millis.
// These will not be exactly multiples of 24*60*60, since there
// might be daylight saving time somewhere inbetween. However, we can
// say that by adding a half day and rounding down afterwards, we always
// get the full days.
long difference = secondSeconds-firstSeconds;
// Adding half a day
if( difference >= 0 ) {
difference += SECONDS_PER_DAY/2; // plus half a day in seconds
} else {
difference -= SECONDS_PER_DAY/2; // minus half a day in seconds
}
// Rounding down to days
difference /= SECONDS_PER_DAY;
return difference;
}
/**
* Truncates a date to the date part alone.
*/
@SuppressWarnings("deprecation")
public static Date truncateToDate(Date d) {
if( d instanceof java.sql.Date ) {
return d; // java.sql.Date is already truncated to date. And raises an
// Exception if we try to set hours, minutes or seconds.
}
d = (Date)d.clone();
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setTime(((d.getTime()/1000)*1000));
return d;
}
答案 11 :(得分:2)
所有这些解决方案都存在两个问题之一。由于舍入错误,闰日和秒数等原因,解决方案都不是完全准确的,或者您最终会在两个未知日期之间循环。
此解决方案解决了第一个问题,并将第二个问题提高了大约365倍,如果您知道最大范围是什么,则会更好。
/**
* @param thisDate
* @param thatDate
* @param maxDays
* set to -1 to not set a max
* @returns number of days covered between thisDate and thatDate, inclusive, i.e., counting both
* thisDate and thatDate as an entire day. Will short out if the number of days exceeds
* or meets maxDays
*/
public static int daysCoveredByDates(Date thisDate, Date thatDate, int maxDays) {
//Check inputs
if (thisDate == null || thatDate == null) {
return -1;
}
//Set calendar objects
Calendar startCal = Calendar.getInstance();
Calendar endCal = Calendar.getInstance();
if (thisDate.before(thatDate)) {
startCal.setTime(thisDate);
endCal.setTime(thatDate);
}
else {
startCal.setTime(thatDate);
endCal.setTime(thisDate);
}
//Get years and dates of our times.
int startYear = startCal.get(Calendar.YEAR);
int endYear = endCal.get(Calendar.YEAR);
int startDay = startCal.get(Calendar.DAY_OF_YEAR);
int endDay = endCal.get(Calendar.DAY_OF_YEAR);
//Calculate the number of days between dates. Add up each year going by until we catch up to endDate.
while (startYear < endYear && maxDays >= 0 && endDay - startDay + 1 < maxDays) {
endDay += startCal.getActualMaximum(Calendar.DAY_OF_YEAR); //adds the number of days in the year startDate is currently in
++startYear;
startCal.set(Calendar.YEAR, startYear); //reup the year
}
int days = endDay - startDay + 1;
//Honor the maximum, if set
if (maxDays >= 0) {
days = Math.min(days, maxDays);
}
return days;
}
如果你需要几天之间的日期(后一个日期无关),当你看到+ 1
时,只需摆脱endDay - startDay + 1
。
答案 12 :(得分:1)
另一种方式:
public static int numberOfDaysBetweenDates(Calendar fromDay, Calendar toDay) {
fromDay = calendarStartOfDay(fromDay);
toDay = calendarStartOfDay(toDay);
long from = fromDay.getTimeInMillis();
long to = toDay.getTimeInMillis();
return (int) TimeUnit.MILLISECONDS.toDays(to - from);
}
答案 13 :(得分:0)
我找到了一种非常简单的方法,这就是我在我的应用中使用的方式。
假设你在Time对象中有日期(或者其他什么,我们只需要几毫秒):
Time date1 = initializeDate1(); //get the date from somewhere
Time date2 = initializeDate2(); //get the date from somewhere
long millis1 = date1.toMillis(true);
long millis2 = date2.toMillis(true);
long difference = millis2 - millis1 ;
//now get the days from the difference and that's it
long days = TimeUnit.MILLISECONDS.toDays(difference);
//now you can do something like
if(days == 7)
{
//do whatever when there's a week of difference
}
if(days >= 30)
{
//do whatever when it's been a month or more
}
答案 14 :(得分:0)
最好的方法是使用Joda-Time,这是您将添加到项目中的非常成功的开源库。
String date1 = "2015-11-11";
String date2 = "2013-11-11";
DateTimeFormatter formatter = new DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime d1 = formatter.parseDateTime(date1);
DateTime d2 = formatter.parseDateTime(date2);
long diffInMillis = d2.getMillis() - d1.getMillis();
Duration duration = new Duration(d1, d2);
int days = duration.getStandardDays();
int hours = duration.getStandardHours();
int minutes = duration.getStandardMinutes();
如果您正在使用Android Studio,则很容易添加joda-time。在build.gradle(app)中:
dependencies {
compile 'joda-time:joda-time:2.4'
compile 'joda-time:joda-time:2.4'
compile 'joda-time:joda-time:2.2'
}
答案 15 :(得分:0)
Date userDob = new SimpleDateFormat("yyyy-MM-dd").parse(dob);
Date today = new Date();
long diff = today.getTime() - userDob.getTime();
int numOfDays = (int) (diff / (1000 * 60 * 60 * 24));
int hours = (int) (diff / (1000 * 60 * 60));
int minutes = (int) (diff / (1000 * 60));
int seconds = (int) (diff / (1000));
答案 16 :(得分:0)
使用这些功能
public static int getDateDifference(int previousYear, int previousMonthOfYear, int previousDayOfMonth, int nextYear, int nextMonthOfYear, int nextDayOfMonth, int differenceToCount){
// int differenceToCount = can be any of the following
// Calendar.MILLISECOND;
// Calendar.SECOND;
// Calendar.MINUTE;
// Calendar.HOUR;
// Calendar.DAY_OF_MONTH;
// Calendar.MONTH;
// Calendar.YEAR;
// Calendar.----
Calendar previousDate = Calendar.getInstance();
previousDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth);
// month is zero indexed so month should be minus 1
previousDate.set(Calendar.MONTH, previousMonthOfYear);
previousDate.set(Calendar.YEAR, previousYear);
Calendar nextDate = Calendar.getInstance();
nextDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth);
// month is zero indexed so month should be minus 1
nextDate.set(Calendar.MONTH, previousMonthOfYear);
nextDate.set(Calendar.YEAR, previousYear);
return getDateDifference(previousDate,nextDate,differenceToCount);
}
public static int getDateDifference(Calendar previousDate,Calendar nextDate,int differenceToCount){
// int differenceToCount = can be any of the following
// Calendar.MILLISECOND;
// Calendar.SECOND;
// Calendar.MINUTE;
// Calendar.HOUR;
// Calendar.DAY_OF_MONTH;
// Calendar.MONTH;
// Calendar.YEAR;
// Calendar.----
//raise an exception if previous is greater than nextdate.
if(previousDate.compareTo(nextDate)>0){
throw new RuntimeException("Previous Date is later than Nextdate");
}
int difference=0;
while(previousDate.compareTo(nextDate)<=0){
difference++;
previousDate.add(differenceToCount,1);
}
return difference;
}
答案 17 :(得分:0)
public void dateDifferenceExample() {
// Set the date for both of the calendar instance
GregorianCalendar calDate = new GregorianCalendar(2012, 10, 02,5,23,43);
GregorianCalendar cal2 = new GregorianCalendar(2015, 04, 02);
// Get the represented date in milliseconds
long millis1 = calDate.getTimeInMillis();
long millis2 = cal2.getTimeInMillis();
// Calculate difference in milliseconds
long diff = millis2 - millis1;
// Calculate difference in seconds
long diffSeconds = diff / 1000;
// Calculate difference in minutes
long diffMinutes = diff / (60 * 1000);
// Calculate difference in hours
long diffHours = diff / (60 * 60 * 1000);
// Calculate difference in days
long diffDays = diff / (24 * 60 * 60 * 1000);
Toast.makeText(getContext(), ""+diffSeconds, Toast.LENGTH_SHORT).show();
}