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

120 人关注

我试图将一个字符串格式的日期与当前日期进行比较。我是这样做的(还没有测试,但应该可以),但我使用的是废弃的方法。有什么好的建议可以替代吗?谢谢。

P.S. 我真的很讨厌在Java中做Date的事情。有很多方法可以做同样的事情,你真的不确定哪种方法是正确的,因此我在这里提出问题。

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;
    
1 个评论
在2018年,最好的方法并不涉及 Calendar SimpleDateFormat Date 或其他任何早已过时的Java日期和时间类。而是使用 java.time ,现代Java日期和时间API .是的,你可以在Android上使用它。对于旧的安卓系统,见 如何在Android项目中使用ThreeTenABP .
java
android
datetime
nunos
nunos
发布于 2012-05-27
16 个回答
JB Nizet
JB Nizet
发布于 2019-12-29
已采纳
0 人赞同

Your code could be reduced to

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;
    
这当然行得通,我在另一个主题上发表了同样的解决方案,但没有在这里发表,因为同事的速度更快 O_o。
只是想在接受之前确认一下。 谢谢。它工作得很好,而且简明扼要,符合要求。
我认为,应该使用dd/MM/yyyy格式,而不是dd/mm/yyyy,因为 "m "表示分钟,而 "M "表示月份。
使用compareTo()方法不是更好吗?
IntelliJ Amiya
IntelliJ Amiya
发布于 2019-12-29
0 人赞同

你可以使用 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)
 Log.d("Return","getMyTime older than getCurrentDateTime "); 
    
顺便说一下,麻烦的旧日期时间类,如 java.util.Date java.util.Calendar java.text.SimpleDateFormat ,现在已经过时,被 java.time 类。大多数的 java.time functionality is back-ported to Java 6 & Java 7 in the 三联书店-Backport project. Further adapted for earlier Android (<26) in 三田ABP . See How to use 三田ABP… .
assylias
assylias
发布于 2019-12-29
0 人赞同

你可以直接从一个 Date 创建一个 Calendar

Calendar validDate = new GregorianCalendar();
validDate.setTime(strDate);
if (Calendar.getInstance().after(validDate)) {
    catalog_outdated = 1;
    
Rocologo
Rocologo
发布于 2019-12-29
0 人赞同

请注意,正确的格式是("dd/MM/yyyy"),然后代码才能工作。"mm "表示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;
    
Siva krishna
Siva krishna
发布于 2019-12-29
0 人赞同
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
    
Basil Bourque
顺便说一下,麻烦的旧日期时间类,如 java.util.Date java.util.Calendar java.text.SimpleDateFormat ,现在已经过时,被 java.time 类。大多数的 java.time functionality is back-ported to Java 6 & Java 7 in the 三联书店-Backport project. Further adapted for earlier Android (<26) in 三田ABP . See How to use 三田ABP… .
Dilavar Malek
Dilavar Malek
发布于 2019-12-29
0 人赞同
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的帮助下检查之前和相等。

Nuno Gonçalves
Nuno Gonçalves
发布于 2019-12-29
0 人赞同

将日期转换成日历,然后在那里进行计算。)

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;
    
请不要混淆任何人......mm和MM是不一样的!
@Muklas 😱 8年了,这一直是个错误!😱更新!
Ole V.V.
Ole V.V.
发布于 2019-12-29
0 人赞同

是时候说说现代的答案了。

java.time and 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对象已经是之后(所以不等于)一个Date对象从解析15/02/2019。这使一些人感到困惑。与此相反,现代的LocalDate是一个没有时间的日期(也没有时区),所以两个代表今天的日期的LocalDate总是相等的。

Question: Can I use java.time on Android?

是的,java.time在旧的和新的安卓设备上都能很好地工作。它只是要求至少有爪哇6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In 爪哇6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
  • Links

  • Oracle tutorial: Date Time explaining how to use java.time.
  • Java Specification Request (JSR) 310, where java.time was first described.
  • ThreeTen Backport project, the backport of java.time to 爪哇6 and 7 (ThreeTen for JSR-310).
  • ThreeTenABP, Android edition of ThreeTen Backport
  • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
  • flame3
    flame3
    发布于 2019-12-29
    0 人赞同

    在Kotlin中,通过内置的函数after()或before()来比较两个时间对象是非常简单的。

    expirationTime.after(Date())
        
    Kirit  Vaghela
    Kirit Vaghela
    发布于 2019-12-29
    0 人赞同
    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));
    

    将此日历所代表的时间与给定日历所代表的时间进行比较。

    如果两个日历的时间相等,则返回0;如果这个日历的时间在另一个日历之前,则返回-1;如果这个日历的时间在另一个日历之后,则返回1。

    谢谢......它帮助了我。
    Cabezas
    Cabezas
    发布于 2019-12-29
    0 人赞同

    有时我们需要做一个带日期的清单,比如说

    今天有小时

    昨日与昨日

    其他日子与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而这post.

    Anurag Ramdasan
    Anurag Ramdasan
    发布于 2019-12-29
    0 人赞同

    You could try this

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

    Basil Bourque
    Basil Bourque
    发布于 2019-12-29
    0 人赞同

    更新。 The 约达-时间 库现在处于维护模式,并建议迁移到 java.time 继承它的框架。参见 由Ole V.V.回答 .

    约达-时间

    java.util.Date和.Calendar类是臭名昭著的麻烦。避免使用它们。使用 约达-时间 或Java 8中新的java.time包。

    LocalDate

    如果你想只用日期而不用时间,那么就用LocalDate类。

    Time Zone

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

    Example in 约达-时间 2.3.

    DateTimeFormat formatter = DateTimeFormat.forPattern( "d/M/yyyy" );
    LocalDate localDate = formatter.parseLocalDate( "1/1/1990" );
    boolean outdated = LocalDate.now( DateTimeZone.UTC ).isAfter( localDate );
        
    phlogratos
    phlogratos
    发布于 2019-12-29
    0 人赞同

    你可以使用 validDate.setTime(strDate) 请看一下下面的javadoc http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html

    kartik_g
    kartik_g
    发布于 2019-12-29
    0 人赞同
    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..//
        
    Khaled Qasem
    Khaled Qasem
    发布于 2019-12-29
    0 人赞同

    Kotlin支持运算符重载

    在Kotlin中,你可以轻松地用比较运算符来比较日期。因为Kotlin已经支持操作符重载。 因此,要比较日期对象。

    firstDate: Date = // your first date
    secondDate: Date = // your second date
    if(firstDate < secondDate){
    // fist date is before second date
    

    而如果你使用的是日历对象,你可以很容易地像这样进行比较。