我已经编写了以下代码,以查找两个日期之间的天数
startDateValue = new Date(startDate);
endDateValue = new Date(endDate);
long diff = endDateValue.getTime() - startDateValue.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = (hours / 24) + 1;
Log.d("days", "" + days);
当开始日期和结束日期分别为2/3/2017和3/3/2017时,显示的天数为29。尽管它们是当天显示的。请假。因此,如果一个人休假,他必须选择相同的起点和结束日期。因此,在这种情况下,他已休假两天)。
我在做什么错?谢谢你的宝贵时间。
注意:请不要使用日期构造函数。检查下面接受的答案。使用SimpleDateFormat或Joda时间。已弃用日期构造函数。
您用于生成日期对象的代码:
Date date = new Date("2/3/2017"); //deprecated
您将获得28天的答案
您可以将字符串转换为日期如下:
String dateStr = "2/3/2017";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse(dateStr);
使用上面的模板使您的日期对象。然后使用以下代码在两个日期之间计算天数。希望这能清除这件事。
它可以按以下方式完成:
long diff = endDateValue.getTime() - startDateValue.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
请检查链接
如果您使用joda时间更简单:
int days = Days.daysBetween(date1, date2).getDays();
请检查Jodatime
如何在Java Project中使用Jodatime
kotlin
这是从今天到某个日期计算天数的示例:
val millionSeconds = yourDate.time - Calendar.getInstance().timeInMillis
leftDays.text = TimeUnit.MILLISECONDS.toDays(millionSeconds).toString() + "days"
如果要计算两天,请更改:
val millionSeconds = yourDate1.time - yourDate2.time
应该工作。
public static int getDaysDifference(Date fromDate,Date toDate)
{
if(fromDate==null||toDate==null)
return 0;
return (int)( (toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24));
}
Android
是否完全支持 java-8
?如果是,您可以简单地使用ChronoUnit
类
LocalDate start = LocalDate.of(2017,2,3);
LocalDate end = LocalDate.of(2017,3,3);
System.out.println(ChronoUnit.DAYS.between(start, end)); // 28
或使用formatter
同一件事DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy");
LocalDate start = LocalDate.parse("2/3/2017",formatter);
LocalDate end = LocalDate.parse("3/3/2017",formatter);
System.out.println(ChronoUnit.DAYS.between(start, end)); // 28
java.time和threetenabp
如果我正确理解,您需要从开始日期到结束日期的天数包含。
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
String startDate = "2/3/2017";
String endDate = "3/3/2017";
LocalDate startDateValue = LocalDate.parse(startDate, dateFormatter);
LocalDate endDateValue = LocalDate.parse(endDate, dateFormatter);
long days = ChronoUnit.DAYS.between(startDateValue, endDateValue) + 1;
System.out.println("Days: " + days);
输出:
天:2
ChronoUnit.DAYS.between()
为我们提供了从开始日期(包括结束日期)到 exclusive 的天数。因此,要包括结束日期,我们需要像您在问题中一样添加1天。
您的代码中出了什么问题?
您正在使用Date(String)
构造函数。自1997年以来,该构造函数已被弃用,因为它在跨时区不可行,所以不要使用它。这也很神奇:至少我从来不知道自己得到了什么。显然,2/3/2017
的意思是2017年2月3日,您打算在2017年3月2日。这解释了您为什么获得29.(如果需要,我们可以通过文档拼写出途径,并找出为什么以 2/3/2017
的方式解释了 CC_8,只有我发现毫无意义的浪费时间。)
您无法转换为毫秒。还请注意,不仅问题,而且不仅转换为天数的许多答案是不正确的。这样的转换假设一天总是24小时。由于夏季时间(DST),每天其他时间异常并不总是24小时。所有这些答案都会算出一天的数量很少,例如,如果休假越过 spring Gap 或 spring Forward时夏季时间开始时。
问题:Java.时间不需要Android API级别26?
java.Time在较新的和较新的Android设备上都可以很好地工作。它至少需要 Java 6 。
- 在Java 8及以后以及在新的Android设备上(来自API级别26),现代API是内置的。
- 在非Android Java 6和7中,获得了Threeten Backport,现代阶级的后座(JSR 310的Threeten;请参阅底部的链接)。
- 在(较旧的)Android上使用Threeten Backport的Android版本。它叫做三分之一。并确保您从
org.threeten.bp
导入带有子包的日期和时间类。
链接
- Oracle教程:解释如何使用Java.Time的日期时间。
- Java规范请求(JSR)310,首先描述了
Date(String)
0。 - Threeten Backport Project,
java.time
的Backport到Java 6和7(JSR-310的Threeten)。 - Threetenabp,Threeten Backport的Android Edition
- 问题:如何在Android项目中使用Threetenabp,并具有非常详尽的解释。
您使用哪种日期格式?是d/M/yyyy
还是M/d/yyyy
?
d = day,m =月,yyyy =年
(请参阅:https://developer.android.com/reference/java/text/simpledateformat.html)
然后代码:
public static final String DATE_FORMAT = "d/M/yyyy"; //or use "M/d/yyyy"
public static long getDaysBetweenDates(String start, String end) {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH);
Date startDate, endDate;
long numberOfDays = 0;
try {
startDate = dateFormat.parse(start);
endDate = dateFormat.parse(end);
numberOfDays = getUnitBetweenDates(startDate, endDate, TimeUnit.DAYS);
} catch (ParseException e) {
e.printStackTrace();
}
return numberOfDays;
}
和getUnitBetweenDates
方法:
private static long getUnitBetweenDates(Date startDate, Date endDate, TimeUnit unit) {
long timeDiff = endDate.getTime() - startDate.getTime();
return unit.convert(timeDiff, TimeUnit.MILLISECONDS);
}
非常简单,只需使用日历,为两个日期创建两个实例,转换为毫秒,减去和转换为几天(四舍五入)...基本上:
Calendar startDate = Calendar.getInstance();
startDate.set(mStartYear, mStartMonth, mStartDay);
long startDateMillis = startDate.getTimeInMillis();
Calendar endDate = Calendar.getInstance();
endDate.set(mEndYear, mEndMonth, mEndDay);
long endDateMillis = endDate.getTimeInMillis();
long differenceMillis = endDateMillis - startDateMillis;
int daysDifference = (int) (differenceMillis / (1000 * 60 * 60 * 24));
看过此代码,这对我有帮助,希望它对您有所帮助。
public String get_count_of_days(String Created_date_String, String Expire_date_String) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
Date Created_convertedDate = null, Expire_CovertedDate = null, todayWithZeroTime = null;
try {
Created_convertedDate = dateFormat.parse(Created_date_String);
Expire_CovertedDate = dateFormat.parse(Expire_date_String);
Date today = new Date();
todayWithZeroTime = dateFormat.parse(dateFormat.format(today));
} catch (ParseException e) {
e.printStackTrace();
}
int c_year = 0, c_month = 0, c_day = 0;
if (Created_convertedDate.after(todayWithZeroTime)) {
Calendar c_cal = Calendar.getInstance();
c_cal.setTime(Created_convertedDate);
c_year = c_cal.get(Calendar.YEAR);
c_month = c_cal.get(Calendar.MONTH);
c_day = c_cal.get(Calendar.DAY_OF_MONTH);
} else {
Calendar c_cal = Calendar.getInstance();
c_cal.setTime(todayWithZeroTime);
c_year = c_cal.get(Calendar.YEAR);
c_month = c_cal.get(Calendar.MONTH);
c_day = c_cal.get(Calendar.DAY_OF_MONTH);
}
/*Calendar today_cal = Calendar.getInstance();
int today_year = today_cal.get(Calendar.YEAR);
int today = today_cal.get(Calendar.MONTH);
int today_day = today_cal.get(Calendar.DAY_OF_MONTH);
*/
Calendar e_cal = Calendar.getInstance();
e_cal.setTime(Expire_CovertedDate);
int e_year = e_cal.get(Calendar.YEAR);
int e_month = e_cal.get(Calendar.MONTH);
int e_day = e_cal.get(Calendar.DAY_OF_MONTH);
Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();
date1.clear();
date1.set(c_year, c_month, c_day);
date2.clear();
date2.set(e_year, e_month, e_day);
long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
float dayCount = (float) diff / (24 * 60 * 60 * 1000);
return ("" + (int) dayCount + " Days");
}
如果您想使用收到的整数,例如在自定义日历实现中指示特定的一天。例如,我尝试通过每月日历视图到每日视图,并通过计算1970-01-01到选定的日期来显示每日视图,并显示每日内容,而每月的25-31天都像一天前一样,因为datesDifferenceInMillis / (24 * 60 * 60 * 1000);
可能会返回17645,9583333333,并且将其投入到INT上,您将获得较低的价值。在这种情况下,您可以通过使用numberNumberFormat类来正确地获得收到的浮点。这是我的代码:
NumberFormat numberFormat = NumberFormat.getInstance(Locale.getDefault());
numberFormat.setRoundingMode(RoundingMode.HALF_UP);
numberFormat.setMaximumFractionDigits(0);
numberFormat.setMinimumFractionDigits(0);
int days = numberFormat.parse(numberFormat.format(value)).intValue();
我希望它会有所帮助。
我在kotlin中修改了jitendra的答案:
fun getDaysBetweenDates(firstDateValue: String, secondDateValue: String, format: String): String
{
val sdf = SimpleDateFormat(format, Locale.getDefault())
val firstDate = sdf.parse(firstDateValue)
val secondDate = sdf.parse(secondDateValue)
if (firstDate == null || secondDate == null)
return 0.toString()
return (((secondDate.time - firstDate.time) / (1000 * 60 * 60 * 24)) + 1).toString()
}
并将其称为
val days = getDaysBetweenDates("31-03-2020", "24-04-2020","dd-MM-yyyy")
fun countDaysBetweenTwoCalendar(calendarStart: Calendar, calendarEnd: Calendar) : Int{
val millionSeconds = calendarEnd.timeInMillis - calendarStart.timeInMillis
val days = TimeUnit.MILLISECONDS.toDays(millionSeconds) //this way not round number
val daysRounded = (millionSeconds / (1000.0 * 60 * 60 * 24)).roundToInt()
return daysRounded
}
虽然这些都不适用于我,但这是一种用非常简单实现代码的简单方法fonction:
private long getDaysDifference(Date fromDate,Date toDate) {
if(fromDate == null || toDate == null)
return 0;
int a = Integer.parseInt(DateFormat.format("dd", fromDate)+"");
int b = Integer.parseInt(DateFormat.format("dd", toDate)+"");
if ( b <= a){
return Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH) + b - a;
}
return b - a;
}
享受
超级简单
使用LocalDate()
包括implementation 'com.jakewharton.threetenabp:threetenabp:1.2.1'
用于Android
示例
在Kotlin
val daysDifferene = LocalDate.of(2017,3,3).toEpochDay() - LocalDate.of(2017,3,2)
甚至更好
创建向LocalDate
class
private operator fun LocalDate.minus(other: LocalDate) = toEpochDay() - other.toEpochDay()
现在只说
val daysDifference = localDate1 - localDate2 // you get number of days in Long type
在Java中
long daysDifference = LocalDate.of(2017,3,3).toEpochDay() - LocalDate.of(2107,3,2)
您可以使用joda时间,太简单
fun getBetweenDates(startDate: Long, endDate: Long): String {
val period = Period(startDate, endDate, PeriodType.yearMonthDayTime())
val formatter = PeriodFormatterBuilder()
.appendYears().appendSuffix(" year ")
.appendMonths().appendSuffix(" month ")
.appendDays().appendSuffix(" days ")
.appendHours().appendSuffix(" hours ")
.appendMinutes().appendSuffix(" minutes ")
.appendSeconds().appendSuffix(" seconds ")
.appendMillis().appendSuffix(" millis ")
.toFormatter()
return formatter.print(period)
}
开始和结束日期毫秒毫秒,结果示例:" 2年1个月..."
使用这种方式:
fun stringDateToCalendar(dateString: String?, formatString: String): Calendar? {
if (dateString == null || dateString.isEmpty() || formatString.isBlank())
return null
val inputDateFormat = SimpleDateFormat(formatString, Locale.ENGLISH)
return try {
inputDateFormat.parse(dateString)?.let {
val cal = Calendar.getInstance()
cal.time = it
cal
}
} catch (e: ParseException) {
null
}
}
val calendarFrom = stringDateToCalendar(
"2021-12-12",
"yyyy-MM-dd"
)
val calendarTo = CalendarUtils.stringDateToCalendar(
"2022-03-20",
"yyyy-MM-dd"
)
val msDiff = calendarTo?.timeInMillis?.minus(calendarFrom?.timeInMillis ?: 0) ?: 0
val daysDiff = TimeUnit.MILLISECONDS.toDays(msDiff)
在这里简单函数kotlin代码
在这里比较这些格式的日期'2022-11-04&quot;" 2022-11-20" >输出将为 16天
open fun dateSubstraction(date1: String, date2: String): String {
val dateFormatter = SimpleDateFormat("yyyy-MM-dd") //Define input date format here
val formatedDate1= dateFormat.parse(date1) //formated date1
val formatedDate2= dateFormat.parse(date2) //formated date2
val millionSeconds = formatedDate2.time - formatedDate1.time
return TimeUnit.MILLISECONDS.toDays(millionSeconds).toString()+"Days"
}
我过去做过这项工作。这很简单
val currentCalendar = Calendar.getInstance()
val targetCalendar = Calendar.getInstance().apply {
set(2023, Calendar.APRIL, 9, 23, 59, 59)
}//your input: date, month, and time
val difference = targetCalendar.timeInMillis - currentCalendar.timeInMillis
val differenceInDays = TimeUnit.MILLISECONDS.toDays(difference)
val remainingMonths = differenceInDays / 30//remaining months
val remainingDays = differenceInDays % 30//remaining days
val differenceInSeconds = TimeUnit.MILLISECONDS.toSeconds(difference)
val differenceInMinutes = TimeUnit.MILLISECONDS.toMinutes(difference)
val differenceInHours = TimeUnit.MILLISECONDS.toHours(difference)
val remainingSeconds = differenceInSeconds % 60//remaining seconds
val remainingMinutes = differenceInMinutes % 60//remaining minutes
val remainingHours = differenceInHours % 24// remaining hours
那就是我们已经完成了