两个日期之间的Android差异
Posted
技术标签:
【中文标题】两个日期之间的Android差异【英文标题】:Android difference between Two Dates 【发布时间】:2014-02-12 15:25:29 【问题描述】:我有两个日期:
String date_1="yyyyMMddHHmmss";
String date_2="yyyyMMddHHmmss";
我想打印如下差异:
2d 3h 45m
我该怎么做?谢谢!
【问题讨论】:
android/Java - Date Difference in days的可能重复 见这里***.com/questions/3838527/… 我在这里提供了超级简单的解决方案***.com/a/65551309/10390808 【参考方案1】:DateTimeUtils obj = new DateTimeUtils();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/M/yyyy hh:mm:ss");
try
Date date1 = simpleDateFormat.parse("10/10/2013 11:30:10");
Date date2 = simpleDateFormat.parse("13/10/2013 20:35:55");
obj.printDifference(date1, date2);
catch (ParseException e)
e.printStackTrace();
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate)
//milliseconds
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
System.out.printf(
"%d days, %d hours, %d minutes, %d seconds%n",
elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
输出是:
startDate : Thu Oct 10 11:30:10 SGT 2013
endDate : Sun Oct 13 20:35:55 SGT 2013
different : 291945000
3 days, 9 hours, 5 minutes, 45 seconds
【讨论】:
@DigveshPatel 知道计算月份和年份的方法吗??DateTimeUtils
是什么?
@RaviVaniya 你的类在你的 Utils 中创建。你可以随意命名。使用它的实例在你的类中调用 printDifference 方法。
在获得毫秒差异之前检查是否 (endDate.after(startDate)) 是否结束日期已超过开始日期。否则
如何只显示一个时间单位?例如:如果只有分钟大于0,我显示分钟,但如果小时大于0,我只显示小时,但是如果天大于0,则在输出中只显示天的单位【参考方案2】:
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));
【讨论】:
这里的dob
是什么?
@KarthicSrinivasan DateOfBirth in millis【参考方案3】:
又短又甜:
/**
* Get a diff between two dates
*
* @param oldDate the old date
* @param newDate the new date
* @return the diff value, in the days
*/
public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate)
try
return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS);
catch (Exception e)
e.printStackTrace();
return 0;
用法:
int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);
输出:
dateDifference: 2
Kotlin 版本:
@ExperimentalTime
fun getDateDiff(format: SimpleDateFormat, oldDate: String, newDate: String): Long
return try
DurationUnit.DAYS.convert(
format.parse(newDate).time - format.parse(oldDate).time,
DurationUnit.MILLISECONDS
)
catch (e: Exception)
e.printStackTrace()
0
【讨论】:
不错的方法。更简单的说MILLISECONDS.toDays(...)
【参考方案4】:
这工作并转换为字符串作为奖励;)
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try
//Dates to compare
String CurrentDate= "09/24/2015";
String FinalDate= "09/26/2015";
Date date1;
Date date2;
SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");
//Setting dates
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);
//Comparing dates
long difference = Math.abs(date1.getTime() - date2.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);
//Convert long to String
String dayDifference = Long.toString(differenceDates);
Log.e("HERE","HERE: " + dayDifference);
catch (Exception exception)
Log.e("DIDN'T WORK", "exception " + exception);
【讨论】:
这个答案对于获取天差非常有用。 @TheVince23 我正在使用上面的代码..但是如果日期在不同的月份,结果是错误的..你能检查一下link【参考方案5】:它会给你几个月的差异
long milliSeconds1 = calendar1.getTimeInMillis();
long milliSeconds2 = calendar2.getTimeInMillis();
long periodSeconds = (milliSeconds2 - milliSeconds1) / 1000;
long elapsedDays = periodSeconds / 60 / 60 / 24;
System.out.println(String.format("%d months", elapsedDays/30));
【讨论】:
这不是月,而是 30 天的倍数。细微的差别。 :)【参考方案6】:我用这个: 以毫秒为单位发送开始和结束日期
public int GetDifference(long start,long end)
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(start);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int min = cal.get(Calendar.MINUTE);
long t=(23-hour)*3600000+(59-min)*60000;
t=start+t;
int diff=0;
if(end>t)
diff=(int)((end-t)/ TimeUnit.DAYS.toMillis(1))+1;
return diff;
【讨论】:
请解释你在代码中做了什么而不是粘贴 sn-p【参考方案7】:您可以使用此方法计算以毫秒为单位的时间差,并以秒、分钟、小时、天、月和年为单位获得输出。
您可以从这里下载课程:DateTimeDifference GitHub Link
使用简单long currentTime = System.currentTimeMillis(); long previousTime = (System.currentTimeMillis() - 864000000); //10天前 Log.d("DateTime: ", "与秒的差异:" + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.SECOND)); Log.d("DateTime: ", "与分钟的差异:" + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE));您可以比较下面的示例
if(AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE) > 100) Log.d("DateTime:", "两个日期相差超过100分钟。"); 别的 Log.d("DateTime:", "两个日期相差不超过100分钟。");
【讨论】:
【参考方案8】:试试这个。
int day = 0;
int hh = 0;
int mm = 0;
try
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy 'at' hh:mm aa");
Date oldDate = dateFormat.parse(oldTime);
Date cDate = new Date();
Long timeDiff = cDate.getTime() - oldDate.getTime();
day = (int) TimeUnit.MILLISECONDS.toDays(timeDiff);
hh = (int) (TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.DAYS.toHours(day));
mm = (int) (TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
catch (ParseException e)
e.printStackTrace();
if (mm <= 60 && hh!= 0)
if (hh <= 60 && day != 0)
return day + " DAYS AGO";
else
return hh + " HOUR AGO";
else
return mm + " MIN AGO";
【讨论】:
【参考方案9】:这是现代答案。这对使用 Java 8 或更高版本(大多数 Android 手机尚不适用)或对外部库感到满意的任何人都有好处。
String date1 = "20170717141000";
String date2 = "20170719175500";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
Duration diff = Duration.between(LocalDateTime.parse(date1, formatter),
LocalDateTime.parse(date2, formatter));
if (diff.isZero())
System.out.println("0m");
else
long days = diff.toDays();
if (days != 0)
System.out.print("" + days + "d ");
diff = diff.minusDays(days);
long hours = diff.toHours();
if (hours != 0)
System.out.print("" + hours + "h ");
diff = diff.minusHours(hours);
long minutes = diff.toMinutes();
if (minutes != 0)
System.out.print("" + minutes + "m ");
diff = diff.minusMinutes(minutes);
long seconds = diff.getSeconds();
if (seconds != 0)
System.out.print("" + seconds + "s ");
System.out.println();
打印出来
2d 3h 45m
在我自己看来,优势不在于它更短(它不多),但将计算留给标准库更不容易出错,并且可以为您提供更清晰的代码。这些都是很大的优势。读者无需承担识别 24、60 和 1000 等常量并验证它们是否正确使用的负担。
我正在使用现代 Java 日期和时间 API(在 JSR-310 中进行了描述,也以此名称为人所知)。要在 API 级别 26 下的 Android 上使用它,请获取 ThreeTenABP,请参阅this question: How to use ThreeTenABP in Android Project。要将其与其他 Java 6 或 7 一起使用,请获取 ThreeTen Backport。在 Java 8 及更高版本中,它是内置的。
使用 Java 9 仍然会更容易一些,因为 Duration
类扩展了一些方法,可以分别为您提供天部分、小时部分、分钟部分和秒部分,因此您不需要减法。请参阅my answer here 中的示例。
【讨论】:
太糟糕了,它需要 API 级别 26 @MShabanAli 这不是真的,但我对此不够清楚,抱歉。我现在将这句话改为:要在 API 级别 26 下的 Android 上使用它,请获取 ThreeTenABP,请参阅 this question: How to use ThreeTenABP in Android Project。 我在答案的开头确实说过:这对任何……对外部库感到满意的人都有好处。【参考方案10】:DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, Locale);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, Locale);
Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()
它返回给定两个日期之间的天数,其中DateTime
来自 joda 库
【讨论】:
不错。我当然同意应该考虑不使用早已过时的Date
和SimpleDateFormat
,即使在Android 上也是如此。他们说比 Joda-Time 更好的是ThreeTenABP。【参考方案11】:
我安排了一点。这很好用。
@SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
Date date = new Date();
String dateOfDay = simpleDateFormat.format(date);
String timeofday = android.text.format.DateFormat.format("HH:mm:ss", new Date().getTime()).toString();
@SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm:ss");
try
Date date1 = dateFormat.parse(06 09 2018 + " " + 10:12:56);
Date date2 = dateFormat.parse(dateOfDay + " " + timeofday);
printDifference(date1, date2);
catch (ParseException e)
e.printStackTrace();
@SuppressLint("SetTextI18n")
private void printDifference(Date startDate, Date endDate)
//milliseconds
long different = endDate.getTime() - startDate.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
Toast.makeText(context, elapsedDays + " " + elapsedHours + " " + elapsedMinutes + " " + elapsedSeconds, Toast.LENGTH_SHORT).show();
【讨论】:
【参考方案12】:当您使用 Date()
计算小时差时,必须在 UTC 中配置 SimpleDateFormat()
,否则由于夏令时会出现一小时错误。
【讨论】:
【参考方案13】:您可以将其概括为一个让您选择输出格式的函数
private String substractDates(Date date1, Date date2, SimpleDateFormat format)
long restDatesinMillis = date1.getTime()-date2.getTime();
Date restdate = new Date(restDatesinMillis);
return format.format(restdate);
现在是这样一个简单的函数调用,时分秒不同:
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try
Date date1 = formater.parse(dateEnd);
Date date2 = formater.parse(dateInit);
String result = substractDates(date1, date2, new SimpleDateFormat("HH:mm:ss"));
txtTime.setText(result);
catch (ParseException e)
e.printStackTrace();
【讨论】:
【参考方案14】:这是一个简单的解决方案:
fun printDaysBetweenTwoDates(): Int
val dateFormat = SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH)
val endDateInMilliSeconds = dateFormat.parse("26-02-2022")?.time ?: 0
val startDateInMilliSeconds = dateFormat.parse("18-02-2022")?.time ?: 0
return getNumberOfDaysBetweenDates(startDateInMilliSeconds, endDateInMilliSeconds)
private fun getNumberOfDaysBetweenDates(
startDateInMilliSeconds: Long,
endDateInMilliSeconds: Long
): Int
val difference = (endDateInMilliSeconds - startDateInMilliSeconds) / (1000 * 60 * 60 * 24).toDouble()
val noOfDays = Math.ceil(difference)
return (noOfDays).toInt()
【讨论】:
以上是关于两个日期之间的Android差异的主要内容,如果未能解决你的问题,请参考以下文章
(Java / Android) 计算两个日期之间的天数并以特定格式呈现结果