Java 如何检查某个日期是否已过去

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24189290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:41:59  来源:igfitidea点击:

How to check if a certain date is passed

javadatecalendar

提问by user2891462

I have a string of the form "mm/yyyy" and I want to compare it against the date of the local system.

我有一个“mm/yyyy”形式的字符串,我想将它与本地系统的日期进行比较。

I have thought of either using a conversion table between my month and the MONTH field in Calendar, something like:

我曾想过在我的月份和日历中的 MONTH 字段之间使用转换表,例如:

    Calendar cal = Calendar.getInstance();
    String date = "07/2014";
    String month = date.subString(0, 2);
    int monthToCompare;
    if (month.equals("01"))
      monthToCompare = cal.JANUARY;
    if (month.equals("02"))
      monthToCompare = cal.FEBRUARY;
    ...

And then comparing manually with an if. I don't like it because I think is way too long for such a simple operation.

然后用 if 手动比较。我不喜欢它,因为我认为对于这样一个简单的操作来说太长了。

The other option I've thought of is getting the current Date()and using the before()method. That would mean translating my date to the Date format, but the easy methods to do it are deprecated, I must specify the number of milliseconds and I do not know how to easily do that (taking into consideration leap years, calendar corrections and so on since 1970).

我想到的另一个选择是获取电流Date()并使用该 before()方法。这意味着将我的日期转换为日期格式,但不推荐使用简单的方法,我必须指定毫秒数,但我不知道如何轻松做到这一点(考虑到闰年、日历更正等)自 1970 年以来)。

采纳答案by user2891462

Using @Mifmif answer I finally solved the problem with:

使用@Mifmif 回答我终于解决了这个问题:

    if (new SimpleDateFormat("MM/yyyy").parse(date).before(new Date())) {
      ...
    }

回答by Mifmif

Try this :

尝试这个 :

new SimpleDateFormat("MM/yyyy").parse("07/2014").compareTo(new Date());

回答by Basil Bourque

tl;dr

tl;博士

YearMonth.parse( 
    "07/2014" , 
    DateTimeFormatter.ofPattern( "MM/uuuu" )
).isAfter(
    YearMonth.now(
        ZoneId.of( "Africa/Tunis" )
    )
)

java.time

时间

The modern solution uses the java.timeclasses rather than the troublesome old date-time classes.

现代解决方案使用java.time类而不是麻烦的旧日期时间类。

Year & month only

仅限年和月

To represent an entire month, use the YearMonthclass.

要表示整个月,请使用YearMonth该类。

String input = "07/2014" ; 
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/uuuu" ) ;
YearMonth ym = YearMonth.parse( input , f ) ;

Tips: Use such YearMonthobjects throughout your codebase rather than a mere string. And when you doneed a string to exchange data, use standard ISO 8601format: YYYY-MM. The java.time classes use standard formats by default when parsing/generating strings, so no need to define formatting pattern.

提示:YearMonth在整个代码库中使用此类对象,而不仅仅是字符串。当您确实需要一个字符串来交换数据时,请使用标准ISO 8601格式:YYYY-MM. java.time 类在解析/生成字符串时默认使用标准格式,因此无需定义格式模式。

Current year-month

当前年月

Determining the current year-month means determining the current date.

确定当前年月意味着确定当前日期。

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris Franceis a new day while still “yesterday” in Montréal Québec.

时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

如果未指定时区,JVM 会隐式应用其当前默认时区。该默认值可能随时更改,因此您的结果可能会有所不同。最好将您想要/预期的时区明确指定为参数。

Specify a proper time zone namein the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as ESTor ISTas they are nottrue time zones, not standardized, and not even unique(!).

以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/regionAmerica/MontrealAfrica/CasablancaPacific/AucklandESTIST

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM's current default time zone, ask for it and pass as an argument. If omitted, the JVM's current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtimeby any code in any thread of any app within the JVM.

如果您想使用 JVM 的当前默认时区,请询问它并作为参数传递。如果省略,则隐式应用 JVM 的当前默认值。最好是明确的,因为JVM 中任何应用程序的任何线程中的任何代码都可能在运行时随时更改默认值。

ZoneId z = ZoneId.systemDefault() ;  // Get JVM's current default time zone.

Same idea applies to getting the current YearMonth: pass a ZoneId.

同样的想法适用于获取当前YearMonth:通过一个ZoneId.

YearMonth currentYearMonth = YearMonth.now( z ) ;

Compare

相比

Compare using methods isBefore, isAfter, and equals.

采用比较的方法isBeforeisAfterequals

boolean isAfterCurrentYearMonth = ym.isAfter( currentYearMonth ) ;


About java.time

关于java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多

回答by Javac Ds

 //getting current date

private String getDateTime() {           

    DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());

    Date date = new Date();

    return dateFormat.format(date);
}


//compare the dates

Date date1  = new Date("second_date to be compared");

Date date2 = new Date(getDateTime());


if(date1.before(date2)) {

     Log.d("Date already passed", " " + "second_date");
}