在 Android 中比较日期的最佳方法

我正在尝试将 String 格式的日期与当前日期进行比较。这就是我是如何做到的(还没有测试,但应该可以工作) ,但是我正在使用不推荐的方法。有什么好的建议吗?谢谢。

另外,我真的很讨厌用爪哇语约会。有很多方法可以做同样的事情,你真的不知道哪一个是正确的,因此我的问题在这里。

String valid_until = "1/1/1990";


Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
Date strDate = sdf.parse(valid_until);


int year = strDate.getYear(); // this is deprecated
int month = strDate.getMonth() // this is deprecated
int day = strDate.getDay(); // this is deprecated


Calendar validDate = Calendar.getInstance();
validDate.set(year, month, day);


Calendar currentDate = Calendar.getInstance();


if (currentDate.after(validDate)) {
catalog_outdated = 1;
}
235193 次浏览

您的代码可以简化为

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
catalog_outdated = 1;
}

或者

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (System.currentTimeMillis() > strDate.getTime()) {
catalog_outdated = 1;
}

您可以直接从 Date创建 Calendar:

Calendar validDate = new GregorianCalendar();
validDate.setTime(strDate);
if (Calendar.getInstance().after(validDate)) {
catalog_outdated = 1;
}

将日期转换为日历并在那里进行计算。 :)

Calendar cal = Calendar.getInstance();
cal.setTime(date);


int year = cal.get(Calendar.YEAR);
int month = cal.geT(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH); //same as cal.get(Calendar.DATE)

或者:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);


if (strDate.after(new Date()) {
catalog_outdated = 1;
}

可以使用 < em > validDate.setTime (strDate) 看一下 javadoc,在 http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html”rel = “ nofollow”> http://docs.oracle.com/javase/1.5.0/docs/api/java/util/calendar.html

你可以试试这个

Calendar today = Calendar.getInstance ();
today.add(Calendar.DAY_OF_YEAR, 0);
today.set(Calendar.HOUR_OF_DAY, hrs);
today.set(Calendar.MINUTE, mins );
today.set(Calendar.SECOND, 0);

您可以使用 today.getTime()检索值并进行比较。

Note that the right format is ("dd/MM/yyyy") before the code works. "mm" means minuts !

String valid_until = "01/07/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = null;
try {
strDate = sdf.parse(valid_until);
} catch (ParseException e) {
e.printStackTrace();
}
if (new Date().after(strDate)) {
catalog_outdated = 1;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();


Date date1 = dateFormat.parse("2013-01-01");
Date date2 = dateFormat.parse("2013-01-02");


calendar1.setTime(date1);
calendar2.setTime(date2);


System.out.println("Compare Result : " + calendar2.compareTo(calendar1));
System.out.println("Compare Result : " + calendar1.compareTo(calendar2));

Compares the time represented by this Calendar to that represented by the given Calendar.

报税表 0 if the times of the two Calendars are equal, -1 if the time of this Calendar is before the other one, 1 if the time of this Calendar is after the other one.

String date = "03/26/2012 11:00:00";
String dateafter = "03/26/2012 11:59:00";
SimpleDateFormat dateFormat = new SimpleDateFormat(
"MM/dd/yyyy hh:mm:ss");
Date convertedDate = new Date();
Date convertedDate2 = new Date();
try {
convertedDate = dateFormat.parse(date);
convertedDate2 = dateFormat.parse(dateafter);
if (convertedDate2.after(convertedDate)) {
txtView.setText("true");
} else {
txtView.setText("false");
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

它返回 true。你也可以在 date.beforedate.equal的帮助下检查前后是否相等。

更新: Joda 时间库现在处于维护模式,建议迁移到继承它的 爪哇时间框架。看看 Ole V.V 回答。


Joda 时间

Java.util.日期及。日历课是出了名的麻烦。避开他们。在 Java8中使用 Joda-Time或新的 Java.time 包。

LocalDate

If you want date-only without time-of-day, then use the LocalDate class.

时区

获取当前日期取决于时区。在蒙特利尔之前,巴黎迎来了一个新的约会。指定所需的时区,而不是依赖于 JVM 的默认值。

Example in Joda-Time 2.3.

DateTimeFormat formatter = DateTimeFormat.forPattern( "d/M/yyyy" );
LocalDate localDate = formatter.parseLocalDate( "1/1/1990" );
boolean outdated = LocalDate.now( DateTimeZone.UTC ).isAfter( localDate );

你可以使用 一个 href = “ https://docs.oracle.com/javase/7/docs/api/java/lang/Compable.html”rel = “ noReferrer”> compareTo ()

如果当前对象较小,则 CompareTo 方法必须返回负数 如果当前对象大于 other object and zero if both objects are equal to each other.

// Get Current Date Time
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm aa");
String getCurrentDateTime = sdf.format(c.getTime());
String getMyTime="05/19/2016 09:45 PM ";
Log.d("getCurrentDateTime",getCurrentDateTime);
// getCurrentDateTime: 05/23/2016 18:49 PM


if (getCurrentDateTime.compareTo(getMyTime) < 0)
{


}
else
{
Log.d("Return","getMyTime older than getCurrentDateTime ");
}
Calendar toDayCalendar = Calendar.getInstance();
Date date1 = toDayCalendar.getTime();




Calendar tomorrowCalendar = Calendar.getInstance();
tomorrowCalendar.add(Calendar.DAY_OF_MONTH,1);
Date date2 = tomorrowCalendar.getTime();


// date1 is a present date and date2 is tomorrow date


if ( date1.compareTo(date2) < 0 ) {


//  0 comes when two date are same,
//  1 comes when date1 is higher then date2
// -1 comes when date1 is lower then date2


}

有时候我们需要列个日期表,比如

今天一小时

昨天和昨天

2017年6月23日的其他日子

To make this we need to compare current time with our data.

Public class DateUtil {


Public static int getDateDayOfMonth (Date date) {
Calendar calendar = Calendar.getInstance ();
Calendar.setTime (date);
Return calendar.get (Calendar.DAY_OF_MONTH);
}


Public static int getCurrentDayOfMonth () {
Calendar calendar = Calendar.getInstance ();
Return calendar.get (Calendar.DAY_OF_MONTH);
}


Public static String convertMillisSecondsToHourString (long millisSecond) {
Date date = new Date (millisSecond);
Format formatter = new SimpleDateFormat ("HH: mm");
Return formatter.format (date);
}


Public static String convertMillisSecondsToDateString (long millisSecond) {
Date date = new Date (millisSecond);
Format formatter = new SimpleDateFormat ("dd / MM / yyyy");
Return formatter.format (date);
}


Public static long convertToMillisSecond (Date date) {
Return date.getTime ();
}


Public static String compare (String stringData, String yesterday) {


String result = "";


SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss");
Date date = null;


Try {
Date = simpleDateFormat.parse (stringData);
} Catch (ParseException e) {
E.printStackTrace ();
}


Long millisSecond = convertToMillisSecond (date);
Long currencyMillisSecond = System.currentTimeMillis ();


If (currencyMillisSecond> millisSecond) {
Long diff = currencyMillisSecond - millisSecond;
Long day = 86400000L;


If (diff <day && getCurrentDayOfMonth () == getDateDayOfMonth (date)) {
Result = convertMillisSecondsToHourString (millisSecond);


} Else if (diff <(day * 2) && getCurrentDayOfMonth () -1 == getDateDayOfMonth (date)) {
Result = yesterday;
} Else {
Result = convertMillisSecondsToDateString (millisSecond);
}
}


Return result;
}
}

你也可以在 GitHub邮寄中检查这个例子。

是时候给出现代的答案了。

Time 和 Three TenABP

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
String validUntil = "1/1/1990";
LocalDate validDate = LocalDate.parse(validUntil, dateFormatter);
LocalDate currentDate = LocalDate.now(ZoneId.of("Pacific/Efate"));
if (currentDate.isAfter(validDate)) {
System.out.println("Catalog is outdated");
}

When I ran this code just now, the output was:

Catalog is outdated

因为在所有的时区,它从来不是相同的日期,所以给 LocalDate.now明确的时区。如果希望目录在所有时区同时过期,只要通知用户正在使用 UTC,就可以给出 ZoneOffset.UTC

I am using java.time, the modern Java date and time API. The date-time classes that you used, Calendar, SimpleDateFormat and Date, are all poorly designed and fortunately long outdated. Also despite the name a Date doesn’t represent a date, but a point in time. One consequence of this is: even though today is February 15, 2019, a newly created Date object is already 之后 (so not equal to) a Date object from parsing 15/02/2019. This confuses some. Contrary to this the modern LocalDate is a date without time of day (and without time zone), so two LocalDates representing today’s date will always be equal.

问: 我可以在 Android 上使用 java.time 吗?

Yes, java.time works nicely on older and newer Android devices. It just requires at least 爪哇6.

  • 在 Java8以及更新的 Android 设备上(从 API 级别26开始) ,现代的 API 是内置的。
  • 在 Java6和 Java7中获得 ThreeTen Backport,这是现代类的 Backport (ThreeTen 表示 JSR 310; 请参阅底部的链接)。
  • 在(旧版本) Android 上使用安卓版本的 ThreeTen Backport。它叫做3TenABP。并确保从 org.threeten.bp导入带有子包的日期和时间类。

连结

SimpleDateFormat sdf=new SimpleDateFormat("d/MM/yyyy");
Date date=null;
Date date1=null;
try {
date=sdf.parse(startDate);
date1=sdf.parse(endDate);
}  catch (ParseException e) {
e.printStackTrace();
}
if (date1.after(date) && date1.equals(date)) {
//..do your work..//
}

Kotlin 支持操作员重载

在 Kotlin,你可以很容易地将日期与比较运算符进行比较,因为 Kotlin 已经支持运算符重载。 比较日期对象:

firstDate: Date = // your first date
secondDate: Date = // your second date


if(firstDate < secondDate){
// fist date is before second date
}


如果你使用的是日历对象,你可以很容易的比较如下:

if(cal1.time < cal2.time){
// cal1 date is before cal2 date
}

在 Kotlin,用内置函数 after ()或 before ()比较两个时间对象非常简单:

expirationTime.after(Date())