繁体   English   中英

比较 Android 中日期的最佳方法

[英]Best way to compare dates in Android

我正在尝试将字符串格式的日期与当前日期进行比较。 这就是我的做法(尚未测试,但应该可以),但我使用的是已弃用的方法。 对替代方案有什么好的建议吗? 谢谢。

PS 我真的很讨厌在 Java 中做日期的事情。做同样的事情有很多方法,你真的不确定哪一个是正确的,因此我的问题在这里。

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;
}

您的代码可以简化为

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;
}

您可以使用compareTo()

如果当前对象小于其他对象,CompareTo 方法必须返回负数,如果当前对象大于其他对象,则返回正数,如果两个对象彼此相等,则返回零。

// 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 "); 
}

您可以直接从Date创建Calendar

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

请注意,在代码工作之前正确的格式是 ("dd/MM/yyyy")。 “mm”表示分钟!

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;
}
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();
}

它返回真。 您还可以在date.beforedate.equal的帮助下检查 before 和 equal 。

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

 }

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

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;
}
try {
  SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

  String str1 = "9/10/2015";
  Date date1 = formatter.parse(str1);

  String str2 = "10/10/2015";
  Date date2 = formatter.parse(str2);

  if (date1.compareTo(date2) < 0) {
    System.out.println("date2 is Greater than my date1");
  }

} catch (ParseException e1) {
  e1.printStackTrace();
}

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

expirationTime.after(Date())
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));

将此 Calendar 表示的时间与给定 Calendar 表示的时间进行比较。

如果两个 Calendar 的时间相等,则返回 0,如果此 Calendar 的时间在另一个 Calendar 之前,则返回 -1,如果此 Calendar 的时间在另一个 Calendar 之后,则返回 1。

现代答案的时间。

java.time 和 ThreeTenABP

    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");
    }

当我刚刚运行这段代码时,输​​出是:

目录已过时

由于它在所有时区中的日期永远不会相同,因此请为LocalDate.now指定明确的时区。 如果您希望目录在所有时区同时到期,您可以提供ZoneOffset.UTC ,只要您通知您的用户您正在使用 UTC。

我正在使用 java.time,现代 Java 日期和时间 API。 您使用的日期时间类CalendarSimpleDateFormatDate都设计得很差,幸运的是已经过时了。 此外,尽管名称Date不代表日期,但代表一个时间点。 这样做的一个后果是:即使今天是 2019 年 2 月 15 日,新创建的Date对象已经(因此不等于)解析15/02/2019Date对象之后。 这让一些人感到困惑。 与此相反,现代LocalDate是没有时间(也没有时区)的日期,因此代表今天日期的两个LocalDate将始终相等。

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

是的,java.time 在较旧和较新的 Android 设备上都能很好地工作。 它只需要至少Java 6

  • 在 Java 8 及更高版本和更新的 Android 设备(从 API 级别 26)中,现代 API 是内置的。
  • 在 Java 6 和 7 中获得 ThreeTen Backport,现代类的 backport(ThreeTen for JSR 310;请参阅底部的链接)。
  • 在(较旧的)Android 上使用 ThreeTen Backport 的 Android 版本。 它被称为 ThreeTenABP。 并确保使用子包从org.threeten.bp导入日期和时间类。

链接

你可以试试这个

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()来检索值并进行比较。

更新: Joda-Time库现在处于维护模式,并建议迁移到继承它的java.time框架。 请参阅Ole VV回答


乔达时间

java.util.Date 和 .Calendar 类是出了名的麻烦。 避开它们。 在 Java 8 中使用Joda-Time或新的 java.time 包。

本地日期

如果您只需要日期而没有时间,请使用 LocalDate 类。

时区

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

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 );

有时我们需要做一个带有日期的列表,比如

今天一小时

昨天和昨天

23/06/2017 的其他日子

为此,我们需要将当前时间与我们的数据进行比较。

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和这篇文章中查看此示例。

您可以使用validDate.setTime(strDate)http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html查看 javadoc

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM