117

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

PS 我真的很讨厌用 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;
}
4

16 回答 16

242

您的代码可以简化为

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;
}
于 2012-05-27T14:58:46.130 回答
26

您可以使用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 "); 
}
于 2016-05-23T13:28:12.993 回答
12

您可以直接Calendar从 a创建一个Date

Calendar validDate = new GregorianCalendar();
validDate.setTime(strDate);
if (Calendar.getInstance().after(validDate)) {
    catalog_outdated = 1;
}
于 2012-05-27T14:59:03.650 回答
11

请注意,在代码工作之前,正确的格式是 ("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;
}
于 2013-05-13T21:35:28.827 回答
8
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();
}

它返回真。您还可以在 and 的帮助下检查之前和date.before相等date.equal

于 2014-06-10T07:55:57.860 回答
8
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-04-06T09:10:48.200 回答
6

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

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;
}
于 2012-05-27T14:59:23.630 回答
2
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。

于 2013-09-30T11:57:32.097 回答
2

是时候给出现代答案了。

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,都设计不佳,幸运的是早已过时。此外,尽管名称 aDate不代表日期,但代表时间点。这样做的一个后果是:即使今天是 2019 年 2 月 15 日,一个新创建的Date对象已经(所以不等于)Date来自 parsing 的对象之后15/02/2019。这让一些人感到困惑。与此相反,现代LocalDate日期是没有时间(也没有时区)的日期,因此LocalDate代表今天日期的两个 s 将始终相等。

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

是的,java.time 在较旧和较新的 Android 设备上运行良好。它只需要至少Java 6

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

链接

于 2019-02-15T14:49:02.360 回答
1

你可以试试这个

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

于 2012-05-27T15:04:00.490 回答
1

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


乔达时间

java.util.Date 和 .Calendar 类是出了名的麻烦。避开他们。使用Joda-Time或 Java 8 中的新 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 );
于 2014-06-11T08:06:51.927 回答
1

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

今天有小时

昨天与昨天

2017 年 6 月 23 日的其他日子

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

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

于 2017-06-23T09:53:30.100 回答
1

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

expirationTime.after(Date())
于 2021-08-25T07:44:26.700 回答
0

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

于 2012-05-27T15:01:28.540 回答
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..//
}
于 2019-11-19T20:12:54.137 回答
0

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
}
于 2019-12-29T14:36:39.380 回答